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 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
251 downloaderBinder
.cancel(mAccount
, mFile
);
252 if (mFile
.isDown()) {
255 setButtonsForRemote();
259 Intent i
= new Intent(getActivity(), FileDownloader
.class);
260 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
261 i
.putExtra(FileDownloader
.EXTRA_FILE
, mFile
);
262 /*i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
263 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
264 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());*/
267 setButtonsForTransferring();
269 getActivity().startService(i
);
270 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
274 case R
.id
.fdKeepInSync
: {
275 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
276 mFile
.setKeepInSync(cb
.isChecked());
277 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
278 fdsm
.saveFile(mFile
);
279 if (mFile
.keepInSync()) {
280 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
282 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
285 Intent intent = new Intent(getActivity().getApplicationContext(),
286 FileObserverService.class);
287 intent.putExtra(FileObserverService.KEY_FILE_CMD,
289 FileObserverService.CMD_ADD_OBSERVED_FILE:
290 FileObserverService.CMD_DEL_OBSERVED_FILE));
291 intent.putExtra(FileObserverService.KEY_CMD_ARG, mFile.getStoragePath());
292 getActivity().startService(intent);
296 case R
.id
.fdRenameBtn
: {
297 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
298 dialog
.show(getFragmentManager(), "nameeditdialog");
299 dialog
.setOnDismissListener(this);
302 case R
.id
.fdRemoveBtn
: {
303 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
304 R
.string
.confirmation_remove_alert
,
305 new String
[]{mFile
.getFileName()},
306 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
307 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
308 R
.string
.common_cancel
);
309 confDialog
.setOnConfirmationListener(this);
310 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
313 case R
.id
.fdOpenBtn
: {
314 String storagePath
= mFile
.getStoragePath();
315 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
317 Intent i
= new Intent(Intent
.ACTION_VIEW
);
318 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
319 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
322 } catch (Throwable t
) {
323 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
324 boolean toastIt
= true
;
325 String mimeType
= "";
327 Intent i
= new Intent(Intent
.ACTION_VIEW
);
328 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
329 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
330 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
331 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
336 } catch (IndexOutOfBoundsException e
) {
337 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
339 } catch (ActivityNotFoundException e
) {
340 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
342 } catch (Throwable th
) {
343 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
347 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
355 Log
.e(TAG
, "Incorrect view clicked!");
358 /* else if (v.getId() == R.id.fdShareBtn) {
359 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
366 public void onConfirmation(String callerTag
) {
367 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
368 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
369 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
370 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
371 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
372 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
378 public void onNeutral(String callerTag
) {
379 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
381 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
383 mFile
.setStoragePath(null
);
384 fdsm
.saveFile(mFile
);
385 updateFileDetails(mFile
, mAccount
);
390 public void onCancel(String callerTag
) {
391 Log
.d(TAG
, "REMOVAL CANCELED");
396 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
398 * @return True when the fragment was created with the empty layout.
400 public boolean isEmpty() {
401 return mLayout
== R
.layout
.file_details_empty
;
406 * Can be used to get the file that is currently being displayed.
407 * @return The file on the screen.
409 public OCFile
getDisplayedFile(){
414 * Use this method to signal this Activity that it shall update its view.
416 * @param file : An {@link OCFile}
418 public void updateFileDetails(OCFile file
, Account ocAccount
) {
420 mAccount
= ocAccount
;
426 * Updates the view with all relevant details about that file.
428 public void updateFileDetails() {
430 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
433 setFilename(mFile
.getFileName());
434 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
436 setFilesize(mFile
.getFileLength());
437 if(ocVersionSupportsTimeCreated()){
438 setTimeCreated(mFile
.getCreationTimestamp());
441 setTimeModified(mFile
.getModificationTimestamp());
443 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
444 cb
.setChecked(mFile
.keepInSync());
446 // configure UI for depending upon local state of the file
447 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
448 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
449 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
450 if ((downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
451 setButtonsForTransferring();
453 } else if (mFile
.isDown()) {
455 if (mFile
.getMimetype().startsWith("image/")) {
456 BitmapLoader bl
= new BitmapLoader();
457 bl
.execute(new String
[]{mFile
.getStoragePath()});
463 setButtonsForRemote();
470 * Updates the filename in view
471 * @param filename to set
473 private void setFilename(String filename
) {
474 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
476 tv
.setText(filename
);
480 * Updates the MIME type in view
481 * @param mimetype to set
483 private void setFiletype(String mimetype
) {
484 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
486 tv
.setText(mimetype
);
490 * Updates the file size in view
491 * @param filesize in bytes to set
493 private void setFilesize(long filesize
) {
494 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
496 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
500 * Updates the time that the file was created in view
501 * @param milliseconds Unix time to set
503 private void setTimeCreated(long milliseconds
){
504 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
505 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
507 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
508 tv
.setVisibility(View
.VISIBLE
);
509 tvLabel
.setVisibility(View
.VISIBLE
);
514 * Updates the time that the file was last modified
515 * @param milliseconds Unix time to set
517 private void setTimeModified(long milliseconds
){
518 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
520 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
525 * Enables or disables buttons for a file being downloaded
527 private void setButtonsForTransferring() {
529 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
530 downloadButton
.setText(R
.string
.common_cancel
);
531 //downloadButton.setEnabled(false);
533 // let's protect the user from himself ;)
534 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
535 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
536 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
541 * Enables or disables buttons for a file locally available
543 private void setButtonsForDown() {
545 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
546 downloadButton
.setText(R
.string
.filedetails_redownload
);
547 //downloadButton.setEnabled(true);
549 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
550 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
551 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
556 * Enables or disables buttons for a file not locally available
558 private void setButtonsForRemote() {
560 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
561 downloadButton
.setText(R
.string
.filedetails_download
);
563 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
564 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
565 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
571 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
572 * the time that the file was created. There is a chance that this will
573 * be fixed in future versions. Use this method to check if this version of
574 * ownCloud has this fix.
575 * @return True, if ownCloud the ownCloud version is supporting creation time
577 private boolean ocVersionSupportsTimeCreated(){
578 /*if(mAccount != null){
579 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
580 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
581 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
582 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
591 * Interface to implement by any Activity that includes some instance of FileDetailFragment
593 * @author David A. Velasco
595 public interface ContainerActivity
extends TransferServiceGetter
{
598 * Callback method invoked when the detail fragment wants to notice its container
599 * activity about a relevant state the file shown by the fragment.
601 * Added to notify to FileDisplayActivity about the need of refresh the files list.
603 * Currently called when:
604 * - a download is started;
605 * - a rename is completed;
606 * - a deletion is completed;
607 * - the 'inSync' flag is changed;
609 public void onFileStateChanged();
615 * Once the file download has finished -> update view
616 * @author Bartek Przybylski
618 private class DownloadFinishReceiver
extends BroadcastReceiver
{
620 public void onReceive(Context context
, Intent intent
) {
621 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
623 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
624 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
625 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
626 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
627 if (downloadWasFine
) {
628 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
630 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
638 * Once the file upload has finished -> update view
640 * Being notified about the finish of an upload is necessary for the next sequence:
641 * 1. Upload a big file.
642 * 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
643 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
644 * 3. Click the file in the list to see its details.
645 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
647 private class UploadFinishReceiver
extends BroadcastReceiver
{
649 public void onReceive(Context context
, Intent intent
) {
650 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
652 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
653 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
654 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
655 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
657 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
658 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
660 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
667 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
668 @SuppressWarnings("unused")
669 private class ShareRunnable
implements Runnable
{
670 private String mPath
;
672 public ShareRunnable(String path
) {
677 AccountManager am
= AccountManager
.get(getActivity());
678 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
679 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
680 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
682 Log
.d("share", "sharing for version " + ocv
.toString());
684 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
685 String APPS_PATH
= "/apps/files_sharing/";
686 String SHARE_PATH
= "ajax/share.php";
688 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
690 final String WEBDAV_SCRIPT
= "webdav.php";
691 final String WEBDAV_FILES_LOCATION
= "/files/";
693 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
694 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
695 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
697 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
698 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
700 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
702 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
703 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
704 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
705 Log
.d("share", mPath
+"");
706 formparams
.add(new BasicNameValuePair("sources",mPath
));
707 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
708 formparams
.add(new BasicNameValuePair("permissions", "0"));
709 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
713 PropFindMethod find
= new PropFindMethod(url
+"/");
714 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
715 Log
.d("sharer", ""+ url
+"/");
717 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
718 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
721 int status2
= wc
.executeMethod(find
);
723 Log
.d("sharer", "propstatus "+status2
);
725 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
726 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
728 status2
= wc
.executeMethod(get
);
730 Log
.d("sharer", "getstatus "+status2
);
731 Log
.d("sharer", "" + get
.getResponseBodyAsString());
733 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
734 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
737 status
= wc
.executeMethod(post
);
738 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
739 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
741 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
742 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
744 String resp
= post
.getResponseBodyAsString();
745 Log
.d("share", ""+post
.getURI().toString());
746 Log
.d("share", "returned status " + status
);
747 Log
.d("share", " " +resp
);
749 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
753 JSONObject jsonObject
= new JSONObject (resp
);
754 String jsonStatus
= jsonObject
.getString("status");
755 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
757 String token
= jsonObject
.getString("data");
758 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
759 Log
.d("Actions:shareFile ok", "url: " + uri
);
761 } catch (Exception e
) {
765 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
771 public void onDismiss(EditNameFragment dialog
) {
772 if (dialog
instanceof EditNameFragment
) {
773 if (((EditNameFragment
)dialog
).getResult()) {
774 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
775 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
776 if (!newFilename
.equals(mFile
.getFileName())) {
777 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
778 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
779 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
780 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
781 newFile
.setFileId(mFile
.getFileId());
782 newFile
.setFileLength(mFile
.getFileLength());
783 newFile
.setKeepInSync(mFile
.keepInSync());
784 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
785 newFile
.setMimetype(mFile
.getMimetype());
786 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
787 newFile
.setParentId(mFile
.getParentId());
788 boolean localRenameFails
= false
;
789 if (mFile
.isDown()) {
790 File f
= new File(mFile
.getStoragePath());
791 Log
.e(TAG
, f
.getAbsolutePath());
792 localRenameFails
= !(f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)));
793 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
794 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
797 if (localRenameFails
) {
798 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
802 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
803 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
804 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
811 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
816 private class RenameRunnable
implements Runnable
{
822 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
830 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
831 AccountManager am
= AccountManager
.get(getSherlockActivity());
832 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
833 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
834 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
835 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
837 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
838 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
839 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
841 boolean success
= false
;
843 int status
= wc
.executeMethod(move
);
844 success
= move
.succeeded();
845 move
.getResponseBodyAsString(); // exhaust response, although not interesting
846 Log
.d(TAG
, "Move returned status: " + status
);
848 } catch (HttpException e
) {
849 Log
.e(TAG
, "HTTP Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
851 } catch (IOException e
) {
852 Log
.e(TAG
, "I/O Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
854 } catch (Exception e
) {
855 Log
.e(TAG
, "Unexpected exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
858 move
.releaseConnection();
862 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
863 fdsm
.removeFile(mOld
, false
);
866 mHandler
.post(new Runnable() {
869 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
870 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
871 updateFileDetails(mFile
, mAccount
);
872 mContainerActivity
.onFileStateChanged();
877 mHandler
.post(new Runnable() {
880 // undo the local rename
882 File f
= new File(mNew
.getStoragePath());
883 if (!f
.renameTo(new File(mOld
.getStoragePath()))) {
884 // the local rename undoing failed; last chance: save the new local storage path in the old file
885 mFile
.setStoragePath(mNew
.getStoragePath());
886 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
887 fdsm
.saveFile(mFile
);
890 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
891 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
893 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
896 } catch (NotFoundException e
) {
903 private class LocalMoveMethod
extends DavMethodBase
{
905 public LocalMoveMethod(String uri
, String dest
) {
907 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
911 public String
getName() {
916 protected boolean isSuccess(int status
) {
917 return status
== 201 || status
== 204;
923 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
925 private String mNewFilename
;
926 private boolean mResult
;
927 private FileDetailFragment mListener
;
929 static public EditNameFragment
newInstance(String filename
) {
930 EditNameFragment f
= new EditNameFragment();
931 Bundle args
= new Bundle();
932 args
.putString("filename", filename
);
933 f
.setArguments(args
);
938 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
939 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
941 String currentName
= getArguments().getString("filename");
942 if (currentName
== null
)
945 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
946 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
947 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
948 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
949 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
956 public void onClick(View view
) {
957 switch (view
.getId()) {
959 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
962 case R
.id
.cancel
: { // fallthought
964 mListener
.onDismiss(this);
969 void setOnDismissListener(FileDetailFragment listener
) {
970 mListener
= listener
;
973 public String
getNewFilename() {
977 // true if user click ok
978 public boolean getResult() {
984 private class RemoveRunnable
implements Runnable
{
987 OCFile mFileToRemove
;
990 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
991 mFileToRemove
= fileToRemove
;
997 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
998 AccountManager am
= AccountManager
.get(getSherlockActivity());
999 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
1000 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
1001 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
1002 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
1004 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
1006 boolean success
= false
;
1009 status
= wc
.executeMethod(delete
);
1010 success
= (delete
.succeeded());
1011 delete
.getResponseBodyAsString(); // exhaust the response, although not interesting
1012 Log
.d(TAG
, "Delete: returned status " + status
);
1014 } catch (HttpException e
) {
1015 Log
.e(TAG
, "HTTP Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1017 } catch (IOException e
) {
1018 Log
.e(TAG
, "I/O Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1020 } catch (Exception e
) {
1021 Log
.e(TAG
, "Unexpected exception removing file " + mFileToRemove
.getRemotePath(), e
);
1024 delete
.releaseConnection();
1028 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
1029 fdsm
.removeFile(mFileToRemove
, true
);
1030 mHandler
.post(new Runnable() {
1033 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1034 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1036 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1038 if (inDisplayActivity
) {
1040 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1041 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1042 transaction
.commit();
1043 mContainerActivity
.onFileStateChanged();
1046 getActivity().finish();
1049 } catch (NotFoundException e
) {
1050 e
.printStackTrace();
1056 mHandler
.post(new Runnable() {
1059 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1060 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1062 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1065 } catch (NotFoundException e
) {
1066 e
.printStackTrace();
1075 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1076 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1078 protected Bitmap
doInBackground(String
... params
) {
1079 Bitmap result
= null
;
1080 if (params
.length
!= 1) return result
;
1081 String storagePath
= params
[0];
1084 BitmapFactory
.Options options
= new Options();
1085 options
.inScaled
= true
;
1086 options
.inPurgeable
= true
;
1087 options
.inJustDecodeBounds
= true
;
1088 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1089 options
.inPreferQualityOverSpeed
= false
;
1091 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1092 options
.inMutable
= false
;
1095 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1096 options
.inJustDecodeBounds
= false
;
1098 int width
= options
.outWidth
;
1099 int height
= options
.outHeight
;
1101 if (width
>= 2048 || height
>= 2048) {
1102 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1103 options
.inSampleSize
= scale
;
1105 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1106 Point size
= new Point();
1108 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1109 display
.getSize(size
);
1110 screenwidth
= size
.x
;
1112 screenwidth
= display
.getWidth();
1115 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1117 if (width
> screenwidth
) {
1118 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1119 options
.inSampleSize
= scale
;
1122 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1124 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1126 } catch (OutOfMemoryError e
) {
1128 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1130 } catch (NoSuchFieldError e
) {
1132 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1134 } catch (Throwable t
) {
1136 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1141 protected void onPostExecute(Bitmap result
) {
1142 if (result
!= null
&& mPreview
!= null
) {
1143 mPreview
.setImageBitmap(result
);