1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 package com
.owncloud
.android
.ui
.fragment
;
21 import java
.util
.ArrayList
;
22 import java
.util
.List
;
24 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
25 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
26 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
27 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
28 import org
.apache
.http
.HttpStatus
;
29 import org
.apache
.http
.NameValuePair
;
30 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
31 import org
.apache
.http
.message
.BasicNameValuePair
;
32 import org
.apache
.http
.protocol
.HTTP
;
33 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
34 import org
.json
.JSONObject
;
36 import android
.accounts
.Account
;
37 import android
.accounts
.AccountManager
;
38 import android
.annotation
.SuppressLint
;
39 import android
.app
.Activity
;
40 import android
.content
.ActivityNotFoundException
;
41 import android
.content
.BroadcastReceiver
;
42 import android
.content
.Context
;
43 import android
.content
.Intent
;
44 import android
.content
.IntentFilter
;
45 import android
.graphics
.Bitmap
;
46 import android
.graphics
.BitmapFactory
;
47 import android
.graphics
.BitmapFactory
.Options
;
48 import android
.graphics
.Point
;
49 import android
.net
.Uri
;
50 import android
.os
.AsyncTask
;
51 import android
.os
.Bundle
;
52 import android
.os
.Handler
;
53 import android
.support
.v4
.app
.FragmentTransaction
;
54 import android
.util
.Log
;
55 import android
.view
.Display
;
56 import android
.view
.LayoutInflater
;
57 import android
.view
.View
;
58 import android
.view
.View
.OnClickListener
;
59 import android
.view
.ViewGroup
;
60 import android
.webkit
.MimeTypeMap
;
61 import android
.widget
.Button
;
62 import android
.widget
.CheckBox
;
63 import android
.widget
.ImageView
;
64 import android
.widget
.TextView
;
65 import android
.widget
.Toast
;
67 import com
.actionbarsherlock
.app
.SherlockFragment
;
68 import com
.owncloud
.android
.AccountUtils
;
69 import com
.owncloud
.android
.DisplayUtils
;
70 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
71 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
72 import com
.owncloud
.android
.datamodel
.OCFile
;
73 import com
.owncloud
.android
.files
.services
.FileDownloader
;
74 import com
.owncloud
.android
.files
.services
.FileObserverService
;
75 import com
.owncloud
.android
.files
.services
.FileUploader
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
77 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
78 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
79 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
80 import com
.owncloud
.android
.operations
.RemoteOperation
;
81 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
82 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
83 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
84 import com
.owncloud
.android
.operations
.RenameFileOperation
;
85 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
86 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
87 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
88 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
89 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
90 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
92 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
94 import com
.owncloud
.android
.R
;
95 import eu
.alefzero
.webdav
.WebdavClient
;
96 import eu
.alefzero
.webdav
.WebdavUtils
;
99 * This Fragment is used to display the details about a file.
101 * @author Bartek Przybylski
104 public class FileDetailFragment
extends SherlockFragment
implements
105 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
107 public static final String EXTRA_FILE
= "FILE";
108 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
110 private FileDetailFragment
.ContainerActivity mContainerActivity
;
114 private OCFile mFile
;
115 private Account mAccount
;
116 private FileDataStorageManager mStorageManager
;
117 private ImageView mPreview
;
119 private DownloadFinishReceiver mDownloadFinishReceiver
;
120 private UploadFinishReceiver mUploadFinishReceiver
;
122 private Handler mHandler
;
123 private RemoteOperation mLastRemoteOperation
;
125 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
126 public static final String FTAG
= "FileDetails";
127 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
131 * Creates an empty details fragment.
133 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
135 public FileDetailFragment() {
138 mStorageManager
= null
;
139 mLayout
= R
.layout
.file_details_empty
;
144 * Creates a details fragment.
146 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
148 * @param fileToDetail An {@link OCFile} to show in the fragment
149 * @param ocAccount An ownCloud account; needed to start downloads
151 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
152 mFile
= fileToDetail
;
153 mAccount
= ocAccount
;
154 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
155 mLayout
= R
.layout
.file_details_empty
;
157 if(fileToDetail
!= null
&& ocAccount
!= null
) {
158 mLayout
= R
.layout
.file_details_fragment
;
164 public void onCreate(Bundle savedInstanceState
) {
165 super.onCreate(savedInstanceState
);
166 mHandler
= new Handler();
171 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
172 Bundle savedInstanceState
) {
173 super.onCreateView(inflater
, container
, savedInstanceState
);
175 if (savedInstanceState
!= null
) {
176 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
177 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
181 view
= inflater
.inflate(mLayout
, container
, false
);
184 if (mLayout
== R
.layout
.file_details_fragment
) {
185 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
186 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
187 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
188 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
189 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
190 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
191 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
203 public void onAttach(Activity activity
) {
204 super.onAttach(activity
);
206 mContainerActivity
= (ContainerActivity
) activity
;
207 } catch (ClassCastException e
) {
208 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
217 public void onActivityCreated(Bundle savedInstanceState
) {
218 super.onActivityCreated(savedInstanceState
);
219 if (mAccount
!= null
) {
220 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
226 public void onSaveInstanceState(Bundle outState
) {
227 Log
.i(getClass().toString(), "onSaveInstanceState() start");
228 super.onSaveInstanceState(outState
);
229 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
230 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
231 Log
.i(getClass().toString(), "onSaveInstanceState() end");
236 public void onResume() {
239 mDownloadFinishReceiver
= new DownloadFinishReceiver();
240 IntentFilter filter
= new IntentFilter(
241 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
242 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
244 mUploadFinishReceiver
= new UploadFinishReceiver();
245 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
246 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
248 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
252 public void onPause() {
255 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
256 mDownloadFinishReceiver
= null
;
258 getActivity().unregisterReceiver(mUploadFinishReceiver
);
259 mUploadFinishReceiver
= null
;
261 if (mPreview
!= null
) {
267 public View
getView() {
268 return super.getView() == null ? mView
: super.getView();
274 public void onClick(View v
) {
276 case R
.id
.fdDownloadBtn
: {
277 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
278 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
279 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
280 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
281 downloaderBinder
.cancel(mAccount
, mFile
);
282 if (mFile
.isDown()) {
285 setButtonsForRemote();
288 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
289 uploaderBinder
.cancel(mAccount
, mFile
);
290 if (!mFile
.fileExists()) {
291 // TODO make something better
292 if (getActivity() instanceof FileDisplayActivity
) {
294 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
295 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
296 transaction
.commit();
297 mContainerActivity
.onFileStateChanged();
299 getActivity().finish();
302 } else if (mFile
.isDown()) {
305 setButtonsForRemote();
309 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
310 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
311 mLastRemoteOperation
.execute(wc
, this, mHandler
);
314 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
315 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
316 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
321 case R
.id
.fdKeepInSync
: {
322 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
323 mFile
.setKeepInSync(cb
.isChecked());
324 mStorageManager
.saveFile(mFile
);
326 /// register the OCFile instance in the observer service to monitor local updates;
327 /// if necessary, the file is download
328 Intent intent
= new Intent(getActivity().getApplicationContext(),
329 FileObserverService
.class);
330 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
332 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
333 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
334 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
335 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
336 Log
.e(TAG
, "starting observer service");
337 getActivity().startService(intent
);
339 if (mFile
.keepInSync()) {
340 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
344 case R
.id
.fdRenameBtn
: {
345 EditNameDialog dialog
= EditNameDialog
.newInstance(mFile
.getFileName());
346 dialog
.setOnDismissListener(this);
347 dialog
.show(getFragmentManager(), "nameeditdialog");
350 case R
.id
.fdRemoveBtn
: {
351 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
352 R
.string
.confirmation_remove_alert
,
353 new String
[]{mFile
.getFileName()},
354 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
355 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
356 R
.string
.common_cancel
);
357 confDialog
.setOnConfirmationListener(this);
358 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
361 case R
.id
.fdOpenBtn
: {
362 String storagePath
= mFile
.getStoragePath();
363 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
365 Intent i
= new Intent(Intent
.ACTION_VIEW
);
366 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
367 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
370 } catch (Throwable t
) {
371 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
372 boolean toastIt
= true
;
373 String mimeType
= "";
375 Intent i
= new Intent(Intent
.ACTION_VIEW
);
376 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
377 if (mimeType
!= null
&& !mimeType
.equals(mFile
.getMimetype())) {
378 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
379 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
384 } catch (IndexOutOfBoundsException e
) {
385 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
387 } catch (ActivityNotFoundException e
) {
388 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
390 } catch (Throwable th
) {
391 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
395 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
403 Log
.e(TAG
, "Incorrect view clicked!");
406 /* else if (v.getId() == R.id.fdShareBtn) {
407 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
414 public void onConfirmation(String callerTag
) {
415 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
416 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
417 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
420 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
421 mLastRemoteOperation
.execute(wc
, this, mHandler
);
423 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
424 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
430 public void onNeutral(String callerTag
) {
432 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
434 mFile
.setStoragePath(null
);
435 mStorageManager
.saveFile(mFile
);
436 updateFileDetails(mFile
, mAccount
);
441 public void onCancel(String callerTag
) {
442 Log
.d(TAG
, "REMOVAL CANCELED");
447 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
449 * @return True when the fragment was created with the empty layout.
451 public boolean isEmpty() {
452 return mLayout
== R
.layout
.file_details_empty
;
457 * Can be used to get the file that is currently being displayed.
458 * @return The file on the screen.
460 public OCFile
getDisplayedFile(){
465 * Use this method to signal this Activity that it shall update its view.
467 * @param file : An {@link OCFile}
469 public void updateFileDetails(OCFile file
, Account ocAccount
) {
471 if (ocAccount
!= null
&& (
472 mStorageManager
== null
||
473 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
475 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
477 mAccount
= ocAccount
;
483 * Updates the view with all relevant details about that file.
485 public void updateFileDetails() {
487 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
490 setFilename(mFile
.getFileName());
491 setFiletype(DisplayUtils
.convertMIMEtoPrettyPrint(mFile
493 setFilesize(mFile
.getFileLength());
494 if(ocVersionSupportsTimeCreated()){
495 setTimeCreated(mFile
.getCreationTimestamp());
498 setTimeModified(mFile
.getModificationTimestamp());
500 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
501 cb
.setChecked(mFile
.keepInSync());
503 // configure UI for depending upon local state of the file
504 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
505 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
506 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
507 if ((downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
508 setButtonsForTransferring();
510 } else if (mFile
.isDown()) {
512 if (mFile
.getMimetype().startsWith("image/")) {
513 BitmapLoader bl
= new BitmapLoader();
514 bl
.execute(new String
[]{mFile
.getStoragePath()});
520 setButtonsForRemote();
527 * Updates the filename in view
528 * @param filename to set
530 private void setFilename(String filename
) {
531 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
533 tv
.setText(filename
);
537 * Updates the MIME type in view
538 * @param mimetype to set
540 private void setFiletype(String mimetype
) {
541 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
543 tv
.setText(mimetype
);
547 * Updates the file size in view
548 * @param filesize in bytes to set
550 private void setFilesize(long filesize
) {
551 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
553 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
557 * Updates the time that the file was created in view
558 * @param milliseconds Unix time to set
560 private void setTimeCreated(long milliseconds
){
561 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
562 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
564 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
565 tv
.setVisibility(View
.VISIBLE
);
566 tvLabel
.setVisibility(View
.VISIBLE
);
571 * Updates the time that the file was last modified
572 * @param milliseconds Unix time to set
574 private void setTimeModified(long milliseconds
){
575 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
577 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
582 * Enables or disables buttons for a file being downloaded
584 private void setButtonsForTransferring() {
586 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
587 downloadButton
.setText(R
.string
.common_cancel
);
588 //downloadButton.setEnabled(false);
590 // let's protect the user from himself ;)
591 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
592 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
593 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
594 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
599 * Enables or disables buttons for a file locally available
601 private void setButtonsForDown() {
603 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
604 downloadButton
.setText(R
.string
.filedetails_sync_file
);
605 //downloadButton.setEnabled(true);
607 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
608 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
609 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
610 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
615 * Enables or disables buttons for a file not locally available
617 private void setButtonsForRemote() {
619 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
620 downloadButton
.setText(R
.string
.filedetails_download
);
622 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
623 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
624 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
625 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
631 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
632 * the time that the file was created. There is a chance that this will
633 * be fixed in future versions. Use this method to check if this version of
634 * ownCloud has this fix.
635 * @return True, if ownCloud the ownCloud version is supporting creation time
637 private boolean ocVersionSupportsTimeCreated(){
638 /*if(mAccount != null){
639 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
640 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
641 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
642 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
651 * Interface to implement by any Activity that includes some instance of FileDetailFragment
653 * @author David A. Velasco
655 public interface ContainerActivity
extends TransferServiceGetter
{
658 * Callback method invoked when the detail fragment wants to notice its container
659 * activity about a relevant state the file shown by the fragment.
661 * Added to notify to FileDisplayActivity about the need of refresh the files list.
663 * Currently called when:
664 * - a download is started;
665 * - a rename is completed;
666 * - a deletion is completed;
667 * - the 'inSync' flag is changed;
669 public void onFileStateChanged();
675 * Once the file download has finished -> update view
676 * @author Bartek Przybylski
678 private class DownloadFinishReceiver
extends BroadcastReceiver
{
680 public void onReceive(Context context
, Intent intent
) {
681 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
683 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
684 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
685 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
686 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
687 if (downloadWasFine
) {
688 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
690 updateFileDetails(); // it updates the buttons; must be called although !downloadWasFine
698 * Once the file upload has finished -> update view
700 * Being notified about the finish of an upload is necessary for the next sequence:
701 * 1. Upload a big file.
702 * 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
703 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
704 * 3. Click the file in the list to see its details.
705 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
707 private class UploadFinishReceiver
extends BroadcastReceiver
{
709 public void onReceive(Context context
, Intent intent
) {
710 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
712 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
713 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
714 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
715 if (mFile
.getRemotePath().equals(uploadRemotePath
)) {
717 FileDataStorageManager fdsm
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
718 mFile
= fdsm
.getFileByPath(mFile
.getRemotePath());
720 updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
727 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
728 @SuppressWarnings("unused")
729 private class ShareRunnable
implements Runnable
{
730 private String mPath
;
732 public ShareRunnable(String path
) {
737 AccountManager am
= AccountManager
.get(getActivity());
738 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
739 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
740 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
742 Log
.d("share", "sharing for version " + ocv
.toString());
744 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
745 String APPS_PATH
= "/apps/files_sharing/";
746 String SHARE_PATH
= "ajax/share.php";
748 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
750 final String WEBDAV_SCRIPT
= "webdav.php";
751 final String WEBDAV_FILES_LOCATION
= "/files/";
753 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
754 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
755 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
757 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
758 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
760 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
762 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
763 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
764 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
765 Log
.d("share", mPath
+"");
766 formparams
.add(new BasicNameValuePair("sources",mPath
));
767 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
768 formparams
.add(new BasicNameValuePair("permissions", "0"));
769 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
773 PropFindMethod find
= new PropFindMethod(url
+"/");
774 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
775 Log
.d("sharer", ""+ url
+"/");
777 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
778 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
781 int status2
= wc
.executeMethod(find
);
783 Log
.d("sharer", "propstatus "+status2
);
785 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
786 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
788 status2
= wc
.executeMethod(get
);
790 Log
.d("sharer", "getstatus "+status2
);
791 Log
.d("sharer", "" + get
.getResponseBodyAsString());
793 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
794 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
797 status
= wc
.executeMethod(post
);
798 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
799 Log
.d("sharer-h", a
.getName() + ":"+a
.getValue());
801 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
802 Log
.d("sharer", a
.getName() + ":"+a
.getValue());
804 String resp
= post
.getResponseBodyAsString();
805 Log
.d("share", ""+post
.getURI().toString());
806 Log
.d("share", "returned status " + status
);
807 Log
.d("share", " " +resp
);
809 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
813 JSONObject jsonObject
= new JSONObject (resp
);
814 String jsonStatus
= jsonObject
.getString("status");
815 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
817 String token
= jsonObject
.getString("data");
818 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
819 Log
.d("Actions:shareFile ok", "url: " + uri
);
821 } catch (Exception e
) {
825 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
831 public void onDismiss(EditNameDialog dialog
) {
832 if (dialog
.getResult()) {
833 String newFilename
= dialog
.getNewFilename();
834 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
835 mLastRemoteOperation
= new RenameFileOperation( mFile
,
837 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
838 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
839 mLastRemoteOperation
.execute(wc
, this, mHandler
);
840 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
841 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
846 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
847 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
849 protected Bitmap
doInBackground(String
... params
) {
850 Bitmap result
= null
;
851 if (params
.length
!= 1) return result
;
852 String storagePath
= params
[0];
855 BitmapFactory
.Options options
= new Options();
856 options
.inScaled
= true
;
857 options
.inPurgeable
= true
;
858 options
.inJustDecodeBounds
= true
;
859 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
860 options
.inPreferQualityOverSpeed
= false
;
862 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
863 options
.inMutable
= false
;
866 result
= BitmapFactory
.decodeFile(storagePath
, options
);
867 options
.inJustDecodeBounds
= false
;
869 int width
= options
.outWidth
;
870 int height
= options
.outHeight
;
872 if (width
>= 2048 || height
>= 2048) {
873 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
874 options
.inSampleSize
= scale
;
876 Display display
= getActivity().getWindowManager().getDefaultDisplay();
877 Point size
= new Point();
879 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
880 display
.getSize(size
);
881 screenwidth
= size
.x
;
883 screenwidth
= display
.getWidth();
886 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
888 if (width
> screenwidth
) {
889 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
890 options
.inSampleSize
= scale
;
893 result
= BitmapFactory
.decodeFile(storagePath
, options
);
895 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
897 } catch (OutOfMemoryError e
) {
899 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
901 } catch (NoSuchFieldError e
) {
903 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
905 } catch (Throwable t
) {
907 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
912 protected void onPostExecute(Bitmap result
) {
913 if (result
!= null
&& mPreview
!= null
) {
914 mPreview
.setImageBitmap(result
);
924 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
925 if (operation
.equals(mLastRemoteOperation
)) {
926 if (operation
instanceof RemoveFileOperation
) {
927 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
929 } else if (operation
instanceof RenameFileOperation
) {
930 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
932 } else if (operation
instanceof SynchronizeFileOperation
) {
933 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
939 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
940 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
941 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
943 if (result
.isSuccess()) {
944 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
946 if (inDisplayActivity
) {
948 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
949 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
950 transaction
.commit();
951 mContainerActivity
.onFileStateChanged();
953 getActivity().finish();
957 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
959 if (result
.isSslRecoverableException()) {
960 // TODO show the SSL warning dialog
965 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
966 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
967 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
969 if (result
.isSuccess()) {
970 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
971 mContainerActivity
.onFileStateChanged();
974 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
975 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
977 // TODO throw again the new rename dialog
979 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
981 if (result
.isSslRecoverableException()) {
982 // TODO show the SSL warning dialog
988 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
989 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
990 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
992 if (!result
.isSuccess()) {
993 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
994 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
995 //i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
996 i
.putExtra("remotepath", mFile
.getRemotePath());
997 i
.putExtra("localpath", mFile
.getStoragePath());
998 i
.putExtra("account", mAccount
);
1002 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1006 if (mFile
.isDown()) {
1007 setButtonsForDown();
1010 setButtonsForRemote();
1014 if (operation
.transferWasRequested()) {
1015 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1016 // checking the service to see if the file is downloading results in FALSE
1018 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1020 if (mFile
.isDown()) {
1021 setButtonsForDown();
1024 setButtonsForRemote();