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
.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
.JSONObject
;
40 import android
.accounts
.Account
;
41 import android
.accounts
.AccountManager
;
42 import android
.annotation
.SuppressLint
;
43 import android
.app
.Activity
;
44 import android
.content
.ActivityNotFoundException
;
45 import android
.content
.BroadcastReceiver
;
46 import android
.content
.Context
;
47 import android
.content
.Intent
;
48 import android
.content
.IntentFilter
;
49 import android
.content
.res
.Resources
.NotFoundException
;
50 import android
.graphics
.Bitmap
;
51 import android
.graphics
.BitmapFactory
;
52 import android
.graphics
.BitmapFactory
.Options
;
53 import android
.graphics
.Point
;
54 import android
.net
.Uri
;
55 import android
.os
.AsyncTask
;
56 import android
.os
.Bundle
;
57 import android
.os
.Handler
;
58 import android
.support
.v4
.app
.FragmentTransaction
;
59 import android
.util
.Log
;
60 import android
.view
.Display
;
61 import android
.view
.LayoutInflater
;
62 import android
.view
.View
;
63 import android
.view
.View
.OnClickListener
;
64 import android
.view
.ViewGroup
;
65 import android
.view
.WindowManager
.LayoutParams
;
66 import android
.webkit
.MimeTypeMap
;
67 import android
.widget
.Button
;
68 import android
.widget
.CheckBox
;
69 import android
.widget
.ImageView
;
70 import android
.widget
.TextView
;
71 import android
.widget
.Toast
;
73 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
74 import com
.actionbarsherlock
.app
.SherlockFragment
;
75 import com
.owncloud
.android
.AccountUtils
;
76 import com
.owncloud
.android
.DisplayUtils
;
77 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
78 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
79 import com
.owncloud
.android
.datamodel
.OCFile
;
80 import com
.owncloud
.android
.files
.services
.FileDownloader
;
81 import com
.owncloud
.android
.files
.services
.FileUploader
;
82 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
83 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
84 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
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
.utils
.OwnCloudVersion
;
90 import com
.owncloud
.android
.R
;
91 import eu
.alefzero
.webdav
.WebdavClient
;
92 import eu
.alefzero
.webdav
.WebdavUtils
;
95 * This Fragment is used to display the details about a file.
97 * @author Bartek Przybylski
100 public class FileDetailFragment
extends SherlockFragment
implements
101 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
103 public static final String EXTRA_FILE
= "FILE";
104 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
106 private FileDetailFragment
.ContainerActivity mContainerActivity
;
110 private OCFile mFile
;
111 private Account mAccount
;
112 private ImageView mPreview
;
114 private DownloadFinishReceiver mDownloadFinishReceiver
;
115 private UploadFinishReceiver mUploadFinishReceiver
;
117 private static final String TAG
= "FileDetailFragment";
118 public static final String FTAG
= "FileDetails";
119 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
123 * Creates an empty details fragment.
125 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
127 public FileDetailFragment() {
130 mLayout
= R
.layout
.file_details_empty
;
135 * Creates a details fragment.
137 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
139 * @param fileToDetail An {@link OCFile} to show in the fragment
140 * @param ocAccount An ownCloud account; needed to start downloads
142 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
143 mFile
= fileToDetail
;
144 mAccount
= ocAccount
;
145 mLayout
= R
.layout
.file_details_empty
;
147 if(fileToDetail
!= null
&& ocAccount
!= null
) {
148 mLayout
= R
.layout
.file_details_fragment
;
154 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
155 Bundle savedInstanceState
) {
156 super.onCreateView(inflater
, container
, savedInstanceState
);
158 if (savedInstanceState
!= null
) {
159 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
160 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
164 view
= inflater
.inflate(mLayout
, container
, false
);
167 if (mLayout
== R
.layout
.file_details_fragment
) {
168 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
169 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
170 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
171 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
172 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
173 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
174 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
186 public void onAttach(Activity activity
) {
187 super.onAttach(activity
);
189 mContainerActivity
= (ContainerActivity
) activity
;
190 } catch (ClassCastException e
) {
191 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getCanonicalName());
197 public void onSaveInstanceState(Bundle outState
) {
198 Log
.i(getClass().toString(), "onSaveInstanceState() start");
199 super.onSaveInstanceState(outState
);
200 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
201 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
202 Log
.i(getClass().toString(), "onSaveInstanceState() end");
207 public void onResume() {
210 mDownloadFinishReceiver
= new DownloadFinishReceiver();
211 IntentFilter filter
= new IntentFilter(
212 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
213 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
215 mUploadFinishReceiver
= new UploadFinishReceiver();
216 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
217 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
219 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
223 public void onPause() {
226 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
227 mDownloadFinishReceiver
= null
;
229 getActivity().unregisterReceiver(mUploadFinishReceiver
);
230 mUploadFinishReceiver
= null
;
232 if (mPreview
!= null
) {
238 public View
getView() {
239 return super.getView() == null ? mView
: super.getView();
245 public void onClick(View v
) {
247 case R
.id
.fdDownloadBtn
: {
248 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
249 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
250 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
251 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
252 downloaderBinder
.cancel(mAccount
, mFile
);
253 if (mFile
.isDown()) {
256 setButtonsForRemote();
259 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
260 uploaderBinder
.cancel(mAccount
, mFile
);
261 if (!mFile
.fileExists()) {
262 // TODO make something better
263 if (getActivity() instanceof FileDisplayActivity
) {
265 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
266 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
267 transaction
.commit();
268 mContainerActivity
.onFileStateChanged();
270 getActivity().finish();
273 } else if (mFile
.isDown()) {
276 setButtonsForRemote();
280 Intent i
= new Intent(getActivity(), FileDownloader
.class);
281 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
282 i
.putExtra(FileDownloader
.EXTRA_FILE
, mFile
);
283 /*i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
284 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
285 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());*/
288 setButtonsForTransferring();
290 getActivity().startService(i
);
291 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
295 case R
.id
.fdKeepInSync
: {
296 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
297 mFile
.setKeepInSync(cb
.isChecked());
298 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
299 fdsm
.saveFile(mFile
);
300 if (mFile
.keepInSync()) {
301 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
303 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
306 Intent intent = new Intent(getActivity().getApplicationContext(),
307 FileObserverService.class);
308 intent.putExtra(FileObserverService.KEY_FILE_CMD,
310 FileObserverService.CMD_ADD_OBSERVED_FILE:
311 FileObserverService.CMD_DEL_OBSERVED_FILE));
312 intent.putExtra(FileObserverService.KEY_CMD_ARG, mFile.getStoragePath());
313 getActivity().startService(intent);
317 case R
.id
.fdRenameBtn
: {
318 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
319 dialog
.show(getFragmentManager(), "nameeditdialog");
320 dialog
.setOnDismissListener(this);
323 case R
.id
.fdRemoveBtn
: {
324 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
325 R
.string
.confirmation_remove_alert
,
326 new String
[]{mFile
.getFileName()},
327 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
328 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
329 R
.string
.common_cancel
);
330 confDialog
.setOnConfirmationListener(this);
331 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
334 case R
.id
.fdOpenBtn
: {
335 String storagePath
= mFile
.getStoragePath();
336 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
338 Intent i
= new Intent(Intent
.ACTION_VIEW
);
339 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
340 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
343 } catch (Throwable t
) {
344 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
345 boolean toastIt
= true
;
346 String mimeType
= "";
348 Intent i
= new Intent(Intent
.ACTION_VIEW
);
349 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
350 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
351 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
352 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
357 } catch (IndexOutOfBoundsException e
) {
358 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
360 } catch (ActivityNotFoundException e
) {
361 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
363 } catch (Throwable th
) {
364 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
368 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
376 Log
.e(TAG
, "Incorrect view clicked!");
379 /* else if (v.getId() == R.id.fdShareBtn) {
380 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
387 public void onConfirmation(String callerTag
) {
388 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
389 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
390 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
391 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
392 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
393 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
399 public void onNeutral(String callerTag
) {
400 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
402 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
404 mFile
.setStoragePath(null
);
405 fdsm
.saveFile(mFile
);
406 updateFileDetails(mFile
, mAccount
);
411 public void onCancel(String callerTag
) {
412 Log
.d(TAG
, "REMOVAL CANCELED");
417 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
419 * @return True when the fragment was created with the empty layout.
421 public boolean isEmpty() {
422 return mLayout
== R
.layout
.file_details_empty
;
427 * Can be used to get the file that is currently being displayed.
428 * @return The file on the screen.
430 public OCFile
getDisplayedFile(){
435 * Use this method to signal this Activity that it shall update its view.
437 * @param file : An {@link OCFile}
439 public void updateFileDetails(OCFile file
, Account ocAccount
) {
441 mAccount
= ocAccount
;
447 * Updates the view with all relevant details about that file.
449 public void updateFileDetails() {
451 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
454 setFilename(mFile
.getFileName());
455 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
457 setFilesize(mFile
.getFileLength());
458 if(ocVersionSupportsTimeCreated()){
459 setTimeCreated(mFile
.getCreationTimestamp());
462 setTimeModified(mFile
.getModificationTimestamp());
464 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
465 cb
.setChecked(mFile
.keepInSync());
467 // configure UI for depending upon local state of the file
468 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
469 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
470 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
471 if ((downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
472 setButtonsForTransferring();
474 } else if (mFile
.isDown()) {
476 if (mFile
.getMimetype().startsWith("image/")) {
477 BitmapLoader bl
= new BitmapLoader();
478 bl
.execute(new String
[]{mFile
.getStoragePath()});
484 setButtonsForRemote();
491 * Updates the filename in view
492 * @param filename to set
494 private void setFilename(String filename
) {
495 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
497 tv
.setText(filename
);
501 * Updates the MIME type in view
502 * @param mimetype to set
504 private void setFiletype(String mimetype
) {
505 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
507 tv
.setText(mimetype
);
511 * Updates the file size in view
512 * @param filesize in bytes to set
514 private void setFilesize(long filesize
) {
515 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
517 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
521 * Updates the time that the file was created in view
522 * @param milliseconds Unix time to set
524 private void setTimeCreated(long milliseconds
){
525 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
526 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
528 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
529 tv
.setVisibility(View
.VISIBLE
);
530 tvLabel
.setVisibility(View
.VISIBLE
);
535 * Updates the time that the file was last modified
536 * @param milliseconds Unix time to set
538 private void setTimeModified(long milliseconds
){
539 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
541 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
546 * Enables or disables buttons for a file being downloaded
548 private void setButtonsForTransferring() {
550 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
551 downloadButton
.setText(R
.string
.common_cancel
);
552 //downloadButton.setEnabled(false);
554 // let's protect the user from himself ;)
555 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
556 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
557 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
558 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
563 * Enables or disables buttons for a file locally available
565 private void setButtonsForDown() {
567 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
568 downloadButton
.setText(R
.string
.filedetails_redownload
);
569 //downloadButton.setEnabled(true);
571 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
572 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
573 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
574 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
579 * Enables or disables buttons for a file not locally available
581 private void setButtonsForRemote() {
583 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
584 downloadButton
.setText(R
.string
.filedetails_download
);
586 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
587 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
588 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
589 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
595 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
596 * the time that the file was created. There is a chance that this will
597 * be fixed in future versions. Use this method to check if this version of
598 * ownCloud has this fix.
599 * @return True, if ownCloud the ownCloud version is supporting creation time
601 private boolean ocVersionSupportsTimeCreated(){
602 /*if(mAccount != null){
603 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
604 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
605 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
606 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
615 * Interface to implement by any Activity that includes some instance of FileDetailFragment
617 * @author David A. Velasco
619 public interface ContainerActivity
extends TransferServiceGetter
{
622 * Callback method invoked when the detail fragment wants to notice its container
623 * activity about a relevant state the file shown by the fragment.
625 * Added to notify to FileDisplayActivity about the need of refresh the files list.
627 * Currently called when:
628 * - a download is started;
629 * - a rename is completed;
630 * - a deletion is completed;
631 * - the 'inSync' flag is changed;
633 public void onFileStateChanged();
639 * Once the file download has finished -> update view
640 * @author Bartek Przybylski
642 private class DownloadFinishReceiver
extends BroadcastReceiver
{
644 public void onReceive(Context context
, Intent intent
) {
645 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
647 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
648 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
649 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
650 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
651 if (downloadWasFine
) {
652 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
654 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
662 * Once the file upload has finished -> update view
664 * Being notified about the finish of an upload is necessary for the next sequence:
665 * 1. Upload a big file.
666 * 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
667 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
668 * 3. Click the file in the list to see its details.
669 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
671 private class UploadFinishReceiver
extends BroadcastReceiver
{
673 public void onReceive(Context context
, Intent intent
) {
674 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
676 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
677 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
678 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
679 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
681 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
682 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
684 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
691 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
692 @SuppressWarnings("unused")
693 private class ShareRunnable
implements Runnable
{
694 private String mPath
;
696 public ShareRunnable(String path
) {
701 AccountManager am
= AccountManager
.get(getActivity());
702 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
703 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
704 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
706 Log
.d("share", "sharing for version " + ocv
.toString());
708 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
709 String APPS_PATH
= "/apps/files_sharing/";
710 String SHARE_PATH
= "ajax/share.php";
712 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
714 final String WEBDAV_SCRIPT
= "webdav.php";
715 final String WEBDAV_FILES_LOCATION
= "/files/";
717 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
718 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
719 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
721 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
722 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
724 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
726 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
727 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
728 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
729 Log
.d("share", mPath
+"");
730 formparams
.add(new BasicNameValuePair("sources",mPath
));
731 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
732 formparams
.add(new BasicNameValuePair("permissions", "0"));
733 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
737 PropFindMethod find
= new PropFindMethod(url
+"/");
738 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
739 Log
.d("sharer", ""+ url
+"/");
741 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
742 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
745 int status2
= wc
.executeMethod(find
);
747 Log
.d("sharer", "propstatus "+status2
);
749 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
750 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
752 status2
= wc
.executeMethod(get
);
754 Log
.d("sharer", "getstatus "+status2
);
755 Log
.d("sharer", "" + get
.getResponseBodyAsString());
757 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
758 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
761 status
= wc
.executeMethod(post
);
762 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
763 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
765 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
766 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
768 String resp
= post
.getResponseBodyAsString();
769 Log
.d("share", ""+post
.getURI().toString());
770 Log
.d("share", "returned status " + status
);
771 Log
.d("share", " " +resp
);
773 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
777 JSONObject jsonObject
= new JSONObject (resp
);
778 String jsonStatus
= jsonObject
.getString("status");
779 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
781 String token
= jsonObject
.getString("data");
782 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
783 Log
.d("Actions:shareFile ok", "url: " + uri
);
785 } catch (Exception e
) {
789 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
795 public void onDismiss(EditNameFragment dialog
) {
796 if (dialog
instanceof EditNameFragment
) {
797 if (((EditNameFragment
)dialog
).getResult()) {
798 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
799 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
800 if (!newFilename
.equals(mFile
.getFileName())) {
801 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
802 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
803 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
804 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
805 newFile
.setFileId(mFile
.getFileId());
806 newFile
.setFileLength(mFile
.getFileLength());
807 newFile
.setKeepInSync(mFile
.keepInSync());
808 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
809 newFile
.setMimetype(mFile
.getMimetype());
810 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
811 newFile
.setParentId(mFile
.getParentId());
812 boolean localRenameFails
= false
;
813 if (mFile
.isDown()) {
814 File f
= new File(mFile
.getStoragePath());
815 Log
.e(TAG
, f
.getAbsolutePath());
816 localRenameFails
= !(f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)));
817 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
818 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
821 if (localRenameFails
) {
822 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
826 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
827 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
828 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
835 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
840 private class RenameRunnable
implements Runnable
{
846 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
854 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
855 AccountManager am
= AccountManager
.get(getSherlockActivity());
856 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
857 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
858 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
859 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
861 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
862 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
863 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
865 boolean success
= false
;
867 int status
= wc
.executeMethod(move
);
868 success
= move
.succeeded();
869 move
.getResponseBodyAsString(); // exhaust response, although not interesting
870 Log
.d(TAG
, "Move returned status: " + status
);
872 } catch (HttpException e
) {
873 Log
.e(TAG
, "HTTP Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
875 } catch (IOException e
) {
876 Log
.e(TAG
, "I/O Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
878 } catch (Exception e
) {
879 Log
.e(TAG
, "Unexpected exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
882 move
.releaseConnection();
886 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
887 fdsm
.removeFile(mOld
, false
);
890 mHandler
.post(new Runnable() {
893 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
894 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
895 updateFileDetails(mFile
, mAccount
);
896 mContainerActivity
.onFileStateChanged();
901 mHandler
.post(new Runnable() {
904 // undo the local rename
906 File f
= new File(mNew
.getStoragePath());
907 if (!f
.renameTo(new File(mOld
.getStoragePath()))) {
908 // the local rename undoing failed; last chance: save the new local storage path in the old file
909 mFile
.setStoragePath(mNew
.getStoragePath());
910 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
911 fdsm
.saveFile(mFile
);
914 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
915 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
917 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
920 } catch (NotFoundException e
) {
927 private class LocalMoveMethod
extends DavMethodBase
{
929 public LocalMoveMethod(String uri
, String dest
) {
931 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
935 public String
getName() {
940 protected boolean isSuccess(int status
) {
941 return status
== 201 || status
== 204;
947 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
949 private String mNewFilename
;
950 private boolean mResult
;
951 private FileDetailFragment mListener
;
953 static public EditNameFragment
newInstance(String filename
) {
954 EditNameFragment f
= new EditNameFragment();
955 Bundle args
= new Bundle();
956 args
.putString("filename", filename
);
957 f
.setArguments(args
);
962 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
963 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
965 String currentName
= getArguments().getString("filename");
966 if (currentName
== null
)
969 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
970 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
971 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
972 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
973 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
980 public void onClick(View view
) {
981 switch (view
.getId()) {
983 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
986 case R
.id
.cancel
: { // fallthought
988 mListener
.onDismiss(this);
993 void setOnDismissListener(FileDetailFragment listener
) {
994 mListener
= listener
;
997 public String
getNewFilename() {
1001 // true if user click ok
1002 public boolean getResult() {
1008 private class RemoveRunnable
implements Runnable
{
1011 OCFile mFileToRemove
;
1014 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
1015 mFileToRemove
= fileToRemove
;
1021 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
1022 AccountManager am
= AccountManager
.get(getSherlockActivity());
1023 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
1024 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
1025 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
1026 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
1028 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
1030 boolean success
= false
;
1033 status
= wc
.executeMethod(delete
);
1034 success
= (delete
.succeeded());
1035 delete
.getResponseBodyAsString(); // exhaust the response, although not interesting
1036 Log
.d(TAG
, "Delete: returned status " + status
);
1038 } catch (HttpException e
) {
1039 Log
.e(TAG
, "HTTP Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1041 } catch (IOException e
) {
1042 Log
.e(TAG
, "I/O Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1044 } catch (Exception e
) {
1045 Log
.e(TAG
, "Unexpected exception removing file " + mFileToRemove
.getRemotePath(), e
);
1048 delete
.releaseConnection();
1052 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
1053 fdsm
.removeFile(mFileToRemove
, true
);
1054 mHandler
.post(new Runnable() {
1057 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1058 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1060 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1062 if (inDisplayActivity
) {
1064 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1065 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1066 transaction
.commit();
1067 mContainerActivity
.onFileStateChanged();
1070 getActivity().finish();
1073 } catch (NotFoundException e
) {
1074 e
.printStackTrace();
1080 mHandler
.post(new Runnable() {
1083 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1084 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1086 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1089 } catch (NotFoundException e
) {
1090 e
.printStackTrace();
1099 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1100 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1102 protected Bitmap
doInBackground(String
... params
) {
1103 Bitmap result
= null
;
1104 if (params
.length
!= 1) return result
;
1105 String storagePath
= params
[0];
1108 BitmapFactory
.Options options
= new Options();
1109 options
.inScaled
= true
;
1110 options
.inPurgeable
= true
;
1111 options
.inJustDecodeBounds
= true
;
1112 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1113 options
.inPreferQualityOverSpeed
= false
;
1115 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1116 options
.inMutable
= false
;
1119 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1120 options
.inJustDecodeBounds
= false
;
1122 int width
= options
.outWidth
;
1123 int height
= options
.outHeight
;
1125 if (width
>= 2048 || height
>= 2048) {
1126 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1127 options
.inSampleSize
= scale
;
1129 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1130 Point size
= new Point();
1132 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1133 display
.getSize(size
);
1134 screenwidth
= size
.x
;
1136 screenwidth
= display
.getWidth();
1139 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1141 if (width
> screenwidth
) {
1142 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1143 options
.inSampleSize
= scale
;
1146 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1148 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1150 } catch (OutOfMemoryError e
) {
1152 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1154 } catch (NoSuchFieldError e
) {
1156 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1158 } catch (Throwable t
) {
1160 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1165 protected void onPostExecute(Bitmap result
) {
1166 if (result
!= null
&& mPreview
!= null
) {
1167 mPreview
.setImageBitmap(result
);