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
.network
.OwnCloudClientUtils
;
84 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
85 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
86 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
87 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
89 import com
.owncloud
.android
.R
;
90 import eu
.alefzero
.webdav
.WebdavClient
;
91 import eu
.alefzero
.webdav
.WebdavUtils
;
94 * This Fragment is used to display the details about a file.
96 * @author Bartek Przybylski
99 public class FileDetailFragment
extends SherlockFragment
implements
100 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
{
102 public static final String EXTRA_FILE
= "FILE";
103 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
105 private FileDetailFragment
.ContainerActivity mContainerActivity
;
109 private OCFile mFile
;
110 private Account mAccount
;
111 private ImageView mPreview
;
113 private DownloadFinishReceiver mDownloadFinishReceiver
;
114 private UploadFinishReceiver mUploadFinishReceiver
;
116 private static final String TAG
= "FileDetailFragment";
117 public static final String FTAG
= "FileDetails";
118 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
122 * Creates an empty details fragment.
124 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
126 public FileDetailFragment() {
129 mLayout
= R
.layout
.file_details_empty
;
134 * Creates a details fragment.
136 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
138 * @param fileToDetail An {@link OCFile} to show in the fragment
139 * @param ocAccount An ownCloud account; needed to start downloads
141 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
142 mFile
= fileToDetail
;
143 mAccount
= ocAccount
;
144 mLayout
= R
.layout
.file_details_empty
;
146 if(fileToDetail
!= null
&& ocAccount
!= null
) {
147 mLayout
= R
.layout
.file_details_fragment
;
153 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
154 Bundle savedInstanceState
) {
155 super.onCreateView(inflater
, container
, savedInstanceState
);
157 if (savedInstanceState
!= null
) {
158 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
159 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
163 view
= inflater
.inflate(mLayout
, container
, false
);
166 if (mLayout
== R
.layout
.file_details_fragment
) {
167 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
168 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
169 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
170 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
171 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
172 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
173 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
185 public void onAttach(Activity activity
) {
186 super.onAttach(activity
);
188 mContainerActivity
= (ContainerActivity
) activity
;
189 } catch (ClassCastException e
) {
190 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getCanonicalName());
196 public void onSaveInstanceState(Bundle outState
) {
197 Log
.i(getClass().toString(), "onSaveInstanceState() start");
198 super.onSaveInstanceState(outState
);
199 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
200 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
201 Log
.i(getClass().toString(), "onSaveInstanceState() end");
206 public void onResume() {
209 mDownloadFinishReceiver
= new DownloadFinishReceiver();
210 IntentFilter filter
= new IntentFilter(
211 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
212 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
214 mUploadFinishReceiver
= new UploadFinishReceiver();
215 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
216 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
218 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
222 public void onPause() {
225 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
226 mDownloadFinishReceiver
= null
;
228 getActivity().unregisterReceiver(mUploadFinishReceiver
);
229 mUploadFinishReceiver
= null
;
231 if (mPreview
!= null
) {
237 public View
getView() {
238 return super.getView() == null ? mView
: super.getView();
244 public void onClick(View v
) {
246 case R
.id
.fdDownloadBtn
: {
247 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
248 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
249 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
250 downloaderBinder
.cancel(mAccount
, mFile
);
251 if (mFile
.isDown()) {
254 setButtonsForRemote();
258 Intent i
= new Intent(getActivity(), FileDownloader
.class);
259 i
.putExtra(FileDownloader
.EXTRA_ACCOUNT
, mAccount
);
260 i
.putExtra(FileDownloader
.EXTRA_FILE
, mFile
);
261 /*i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
262 i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
263 i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());*/
266 setButtonsForTransferring();
268 getActivity().startService(i
);
269 mContainerActivity
.onFileStateChanged(); // this is not working; it is performed before the fileDownloadService registers it as 'in progress'
273 case R
.id
.fdKeepInSync
: {
274 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
275 mFile
.setKeepInSync(cb
.isChecked());
276 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
277 fdsm
.saveFile(mFile
);
278 if (mFile
.keepInSync()) {
279 onClick(getView().findViewById(R
.id
.fdDownloadBtn
));
281 mContainerActivity
.onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the virtual click on fdDownloadBtn)
284 Intent intent = new Intent(getActivity().getApplicationContext(),
285 FileObserverService.class);
286 intent.putExtra(FileObserverService.KEY_FILE_CMD,
288 FileObserverService.CMD_ADD_OBSERVED_FILE:
289 FileObserverService.CMD_DEL_OBSERVED_FILE));
290 intent.putExtra(FileObserverService.KEY_CMD_ARG, mFile.getStoragePath());
291 getActivity().startService(intent);
295 case R
.id
.fdRenameBtn
: {
296 EditNameFragment dialog
= EditNameFragment
.newInstance(mFile
.getFileName());
297 dialog
.show(getFragmentManager(), "nameeditdialog");
298 dialog
.setOnDismissListener(this);
301 case R
.id
.fdRemoveBtn
: {
302 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
303 R
.string
.confirmation_remove_alert
,
304 new String
[]{mFile
.getFileName()},
305 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
306 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
307 R
.string
.common_cancel
);
308 confDialog
.setOnConfirmationListener(this);
309 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
312 case R
.id
.fdOpenBtn
: {
313 String storagePath
= mFile
.getStoragePath();
314 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
316 Intent i
= new Intent(Intent
.ACTION_VIEW
);
317 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
318 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
321 } catch (Throwable t
) {
322 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
323 boolean toastIt
= true
;
324 String mimeType
= "";
326 Intent i
= new Intent(Intent
.ACTION_VIEW
);
327 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
328 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
329 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
330 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
335 } catch (IndexOutOfBoundsException e
) {
336 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
338 } catch (ActivityNotFoundException e
) {
339 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
341 } catch (Throwable th
) {
342 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
346 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
354 Log
.e(TAG
, "Incorrect view clicked!");
357 /* else if (v.getId() == R.id.fdShareBtn) {
358 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
365 public void onConfirmation(String callerTag
) {
366 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
367 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
368 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
369 new Thread(new RemoveRunnable(mFile
, mAccount
, new Handler())).start();
370 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
371 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
377 public void onNeutral(String callerTag
) {
378 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
380 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
382 mFile
.setStoragePath(null
);
383 fdsm
.saveFile(mFile
);
384 updateFileDetails(mFile
, mAccount
);
389 public void onCancel(String callerTag
) {
390 Log
.d(TAG
, "REMOVAL CANCELED");
395 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
397 * @return True when the fragment was created with the empty layout.
399 public boolean isEmpty() {
400 return mLayout
== R
.layout
.file_details_empty
;
405 * Can be used to get the file that is currently being displayed.
406 * @return The file on the screen.
408 public OCFile
getDisplayedFile(){
413 * Use this method to signal this Activity that it shall update its view.
415 * @param file : An {@link OCFile}
417 public void updateFileDetails(OCFile file
, Account ocAccount
) {
419 mAccount
= ocAccount
;
425 * Updates the view with all relevant details about that file.
427 public void updateFileDetails() {
429 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
432 setFilename(mFile
.getFileName());
433 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
435 setFilesize(mFile
.getFileLength());
436 if(ocVersionSupportsTimeCreated()){
437 setTimeCreated(mFile
.getCreationTimestamp());
440 setTimeModified(mFile
.getModificationTimestamp());
442 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
443 cb
.setChecked(mFile
.keepInSync());
445 // configure UI for depending upon local state of the file
446 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
447 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
448 if ((downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || FileUploader
.isUploading(mAccount
, mFile
.getRemotePath())) {
449 setButtonsForTransferring();
451 } else if (mFile
.isDown()) {
453 if (mFile
.getMimetype().startsWith("image/")) {
454 BitmapLoader bl
= new BitmapLoader();
455 bl
.execute(new String
[]{mFile
.getStoragePath()});
461 setButtonsForRemote();
468 * Updates the filename in view
469 * @param filename to set
471 private void setFilename(String filename
) {
472 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
474 tv
.setText(filename
);
478 * Updates the MIME type in view
479 * @param mimetype to set
481 private void setFiletype(String mimetype
) {
482 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
484 tv
.setText(mimetype
);
488 * Updates the file size in view
489 * @param filesize in bytes to set
491 private void setFilesize(long filesize
) {
492 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
494 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
498 * Updates the time that the file was created in view
499 * @param milliseconds Unix time to set
501 private void setTimeCreated(long milliseconds
){
502 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
503 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
505 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
506 tv
.setVisibility(View
.VISIBLE
);
507 tvLabel
.setVisibility(View
.VISIBLE
);
512 * Updates the time that the file was last modified
513 * @param milliseconds Unix time to set
515 private void setTimeModified(long milliseconds
){
516 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
518 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
523 * Enables or disables buttons for a file being downloaded
525 private void setButtonsForTransferring() {
527 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
528 downloadButton
.setText(R
.string
.common_cancel
);
529 //downloadButton.setEnabled(false);
531 // let's protect the user from himself ;)
532 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
533 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
534 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
539 * Enables or disables buttons for a file locally available
541 private void setButtonsForDown() {
543 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
544 downloadButton
.setText(R
.string
.filedetails_redownload
);
545 //downloadButton.setEnabled(true);
547 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
548 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
549 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
554 * Enables or disables buttons for a file not locally available
556 private void setButtonsForRemote() {
558 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
559 downloadButton
.setText(R
.string
.filedetails_download
);
561 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
562 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
563 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
569 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
570 * the time that the file was created. There is a chance that this will
571 * be fixed in future versions. Use this method to check if this version of
572 * ownCloud has this fix.
573 * @return True, if ownCloud the ownCloud version is supporting creation time
575 private boolean ocVersionSupportsTimeCreated(){
576 /*if(mAccount != null){
577 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
578 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
579 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
580 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
589 * Interface to implement by any Activity that includes some instance of FileDetailFragment
591 * @author David A. Velasco
593 public interface ContainerActivity
extends TransferServiceGetter
{
596 * Callback method invoked when the detail fragment wants to notice its container
597 * activity about a relevant state the file shown by the fragment.
599 * Added to notify to FileDisplayActivity about the need of refresh the files list.
601 * Currently called when:
602 * - a download is started;
603 * - a rename is completed;
604 * - a deletion is completed;
605 * - the 'inSync' flag is changed;
607 public void onFileStateChanged();
613 * Once the file download has finished -> update view
614 * @author Bartek Przybylski
616 private class DownloadFinishReceiver
extends BroadcastReceiver
{
618 public void onReceive(Context context
, Intent intent
) {
619 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
621 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
622 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
623 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
624 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
625 if (downloadWasFine
) {
626 mFile
.setStoragePath(intent
.getStringExtra(FileDownloader
.EXTRA_FILE_PATH
)); // updates the local object without accessing the database again
628 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
636 * Once the file upload has finished -> update view
638 * Being notified about the finish of an upload is necessary for the next sequence:
639 * 1. Upload a big file.
640 * 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
641 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
642 * 3. Click the file in the list to see its details.
643 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
645 private class UploadFinishReceiver
extends BroadcastReceiver
{
647 public void onReceive(Context context
, Intent intent
) {
648 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
650 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
651 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
652 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
653 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
655 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
656 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
658 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
665 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
666 @SuppressWarnings("unused")
667 private class ShareRunnable
implements Runnable
{
668 private String mPath
;
670 public ShareRunnable(String path
) {
675 AccountManager am
= AccountManager
.get(getActivity());
676 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
677 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
678 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
680 Log
.d("share", "sharing for version " + ocv
.toString());
682 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
683 String APPS_PATH
= "/apps/files_sharing/";
684 String SHARE_PATH
= "ajax/share.php";
686 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
688 final String WEBDAV_SCRIPT
= "webdav.php";
689 final String WEBDAV_FILES_LOCATION
= "/files/";
691 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
692 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
693 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
695 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
696 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
698 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
700 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
701 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
702 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
703 Log
.d("share", mPath
+"");
704 formparams
.add(new BasicNameValuePair("sources",mPath
));
705 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
706 formparams
.add(new BasicNameValuePair("permissions", "0"));
707 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
711 PropFindMethod find
= new PropFindMethod(url
+"/");
712 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
713 Log
.d("sharer", ""+ url
+"/");
715 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
716 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
719 int status2
= wc
.executeMethod(find
);
721 Log
.d("sharer", "propstatus "+status2
);
723 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
724 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
726 status2
= wc
.executeMethod(get
);
728 Log
.d("sharer", "getstatus "+status2
);
729 Log
.d("sharer", "" + get
.getResponseBodyAsString());
731 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
732 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
735 status
= wc
.executeMethod(post
);
736 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
737 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
739 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
740 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
742 String resp
= post
.getResponseBodyAsString();
743 Log
.d("share", ""+post
.getURI().toString());
744 Log
.d("share", "returned status " + status
);
745 Log
.d("share", " " +resp
);
747 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
751 JSONObject jsonObject
= new JSONObject (resp
);
752 String jsonStatus
= jsonObject
.getString("status");
753 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
755 String token
= jsonObject
.getString("data");
756 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
757 Log
.d("Actions:shareFile ok", "url: " + uri
);
759 } catch (Exception e
) {
763 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
769 public void onDismiss(EditNameFragment dialog
) {
770 if (dialog
instanceof EditNameFragment
) {
771 if (((EditNameFragment
)dialog
).getResult()) {
772 String newFilename
= ((EditNameFragment
)dialog
).getNewFilename();
773 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
774 if (!newFilename
.equals(mFile
.getFileName())) {
775 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
776 if (fdsm
.getFileById(mFile
.getFileId()) != null
) {
777 OCFile newFile
= new OCFile(fdsm
.getFileById(mFile
.getParentId()).getRemotePath() + newFilename
);
778 newFile
.setCreationTimestamp(mFile
.getCreationTimestamp());
779 newFile
.setFileId(mFile
.getFileId());
780 newFile
.setFileLength(mFile
.getFileLength());
781 newFile
.setKeepInSync(mFile
.keepInSync());
782 newFile
.setLastSyncDate(mFile
.getLastSyncDate());
783 newFile
.setMimetype(mFile
.getMimetype());
784 newFile
.setModificationTimestamp(mFile
.getModificationTimestamp());
785 newFile
.setParentId(mFile
.getParentId());
786 boolean localRenameFails
= false
;
787 if (mFile
.isDown()) {
788 File f
= new File(mFile
.getStoragePath());
789 Log
.e(TAG
, f
.getAbsolutePath());
790 localRenameFails
= !(f
.renameTo(new File(f
.getParent() + File
.separator
+ newFilename
)));
791 Log
.e(TAG
, f
.getParent() + File
.separator
+ newFilename
);
792 newFile
.setStoragePath(f
.getParent() + File
.separator
+ newFilename
);
795 if (localRenameFails
) {
796 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
800 new Thread(new RenameRunnable(mFile
, newFile
, mAccount
, new Handler())).start();
801 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
802 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
809 Log
.e(TAG
, "Unknown dialog instance passed to onDismissDalog: " + dialog
.getClass().getCanonicalName());
814 private class RenameRunnable
implements Runnable
{
820 public RenameRunnable(OCFile oldFile
, OCFile newFile
, Account account
, Handler handler
) {
828 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
829 AccountManager am
= AccountManager
.get(getSherlockActivity());
830 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
831 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
832 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
833 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()));
835 Log
.e("ASD", Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
836 LocalMoveMethod move
= new LocalMoveMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mOld
.getRemotePath()),
837 Uri
.parse(baseUrl
).getPath() == null ?
"" : Uri
.parse(baseUrl
).getPath() + webdav_path
+ WebdavUtils
.encodePath(mNew
.getRemotePath()));
839 boolean success
= false
;
841 int status
= wc
.executeMethod(move
);
842 success
= move
.succeeded();
843 move
.getResponseBodyAsString(); // exhaust response, although not interesting
844 Log
.d(TAG
, "Move returned status: " + status
);
846 } catch (HttpException e
) {
847 Log
.e(TAG
, "HTTP Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
849 } catch (IOException e
) {
850 Log
.e(TAG
, "I/O Exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
852 } catch (Exception e
) {
853 Log
.e(TAG
, "Unexpected exception renaming file " + mOld
.getRemotePath() + " to " + mNew
.getRemotePath(), e
);
856 move
.releaseConnection();
860 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
861 fdsm
.removeFile(mOld
, false
);
864 mHandler
.post(new Runnable() {
867 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
868 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
869 updateFileDetails(mFile
, mAccount
);
870 mContainerActivity
.onFileStateChanged();
875 mHandler
.post(new Runnable() {
878 // undo the local rename
880 File f
= new File(mNew
.getStoragePath());
881 if (!f
.renameTo(new File(mOld
.getStoragePath()))) {
882 // the local rename undoing failed; last chance: save the new local storage path in the old file
883 mFile
.setStoragePath(mNew
.getStoragePath());
884 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
885 fdsm
.saveFile(mFile
);
888 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
889 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
891 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
894 } catch (NotFoundException e
) {
901 private class LocalMoveMethod
extends DavMethodBase
{
903 public LocalMoveMethod(String uri
, String dest
) {
905 addRequestHeader(new org
.apache
.commons
.httpclient
.Header("Destination", dest
));
909 public String
getName() {
914 protected boolean isSuccess(int status
) {
915 return status
== 201 || status
== 204;
921 private static class EditNameFragment
extends SherlockDialogFragment
implements OnClickListener
{
923 private String mNewFilename
;
924 private boolean mResult
;
925 private FileDetailFragment mListener
;
927 static public EditNameFragment
newInstance(String filename
) {
928 EditNameFragment f
= new EditNameFragment();
929 Bundle args
= new Bundle();
930 args
.putString("filename", filename
);
931 f
.setArguments(args
);
936 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
, Bundle savedInstanceState
) {
937 View v
= inflater
.inflate(R
.layout
.edit_box_dialog
, container
, false
);
939 String currentName
= getArguments().getString("filename");
940 if (currentName
== null
)
943 ((Button
)v
.findViewById(R
.id
.cancel
)).setOnClickListener(this);
944 ((Button
)v
.findViewById(R
.id
.ok
)).setOnClickListener(this);
945 ((TextView
)v
.findViewById(R
.id
.user_input
)).setText(currentName
);
946 ((TextView
)v
.findViewById(R
.id
.user_input
)).requestFocus();
947 getDialog().getWindow().setSoftInputMode(LayoutParams
.SOFT_INPUT_STATE_VISIBLE
);
954 public void onClick(View view
) {
955 switch (view
.getId()) {
957 mNewFilename
= ((TextView
)getView().findViewById(R
.id
.user_input
)).getText().toString();
960 case R
.id
.cancel
: { // fallthought
962 mListener
.onDismiss(this);
967 void setOnDismissListener(FileDetailFragment listener
) {
968 mListener
= listener
;
971 public String
getNewFilename() {
975 // true if user click ok
976 public boolean getResult() {
982 private class RemoveRunnable
implements Runnable
{
985 OCFile mFileToRemove
;
988 public RemoveRunnable(OCFile fileToRemove
, Account account
, Handler handler
) {
989 mFileToRemove
= fileToRemove
;
995 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
996 AccountManager am
= AccountManager
.get(getSherlockActivity());
997 String baseUrl
= am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
998 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
));
999 String webdav_path
= AccountUtils
.getWebdavPath(ocv
);
1000 Log
.d("ASD", ""+baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
1002 DeleteMethod delete
= new DeleteMethod(baseUrl
+ webdav_path
+ WebdavUtils
.encodePath(mFileToRemove
.getRemotePath()));
1004 boolean success
= false
;
1007 status
= wc
.executeMethod(delete
);
1008 success
= (delete
.succeeded());
1009 delete
.getResponseBodyAsString(); // exhaust the response, although not interesting
1010 Log
.d(TAG
, "Delete: returned status " + status
);
1012 } catch (HttpException e
) {
1013 Log
.e(TAG
, "HTTP Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1015 } catch (IOException e
) {
1016 Log
.e(TAG
, "I/O Exception removing file " + mFileToRemove
.getRemotePath(), e
);
1018 } catch (Exception e
) {
1019 Log
.e(TAG
, "Unexpected exception removing file " + mFileToRemove
.getRemotePath(), e
);
1022 delete
.releaseConnection();
1026 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getContentResolver());
1027 fdsm
.removeFile(mFileToRemove
, true
);
1028 mHandler
.post(new Runnable() {
1031 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1032 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1034 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
1036 if (inDisplayActivity
) {
1038 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
1039 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
1040 transaction
.commit();
1041 mContainerActivity
.onFileStateChanged();
1044 getActivity().finish();
1047 } catch (NotFoundException e
) {
1048 e
.printStackTrace();
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(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
1063 } catch (NotFoundException e
) {
1064 e
.printStackTrace();
1073 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
1074 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
1076 protected Bitmap
doInBackground(String
... params
) {
1077 Bitmap result
= null
;
1078 if (params
.length
!= 1) return result
;
1079 String storagePath
= params
[0];
1082 BitmapFactory
.Options options
= new Options();
1083 options
.inScaled
= true
;
1084 options
.inPurgeable
= true
;
1085 options
.inJustDecodeBounds
= true
;
1086 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
1087 options
.inPreferQualityOverSpeed
= false
;
1089 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
1090 options
.inMutable
= false
;
1093 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1094 options
.inJustDecodeBounds
= false
;
1096 int width
= options
.outWidth
;
1097 int height
= options
.outHeight
;
1099 if (width
>= 2048 || height
>= 2048) {
1100 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
1101 options
.inSampleSize
= scale
;
1103 Display display
= getActivity().getWindowManager().getDefaultDisplay();
1104 Point size
= new Point();
1106 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
1107 display
.getSize(size
);
1108 screenwidth
= size
.x
;
1110 screenwidth
= display
.getWidth();
1113 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
1115 if (width
> screenwidth
) {
1116 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
1117 options
.inSampleSize
= scale
;
1120 result
= BitmapFactory
.decodeFile(storagePath
, options
);
1122 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
1124 } catch (OutOfMemoryError e
) {
1126 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
1128 } catch (NoSuchFieldError e
) {
1130 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
1132 } catch (Throwable t
) {
1134 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
1139 protected void onPostExecute(Bitmap result
) {
1140 if (result
!= null
&& mPreview
!= null
) {
1141 mPreview
.setImageBitmap(result
);