1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.ui
.fragment
;
22 import java
.util
.ArrayList
;
23 import java
.util
.List
;
25 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
26 import org
.apache
.commons
.httpclient
.methods
.PostMethod
;
27 import org
.apache
.commons
.httpclient
.methods
.StringRequestEntity
;
28 import org
.apache
.commons
.httpclient
.params
.HttpConnectionManagerParams
;
29 import org
.apache
.http
.HttpStatus
;
30 import org
.apache
.http
.NameValuePair
;
31 import org
.apache
.http
.client
.utils
.URLEncodedUtils
;
32 import org
.apache
.http
.message
.BasicNameValuePair
;
33 import org
.apache
.http
.protocol
.HTTP
;
34 import org
.apache
.jackrabbit
.webdav
.client
.methods
.PropFindMethod
;
35 import org
.json
.JSONObject
;
37 import android
.accounts
.Account
;
38 import android
.accounts
.AccountManager
;
39 import android
.annotation
.SuppressLint
;
40 import android
.app
.Activity
;
41 import android
.content
.ActivityNotFoundException
;
42 import android
.content
.BroadcastReceiver
;
43 import android
.content
.Context
;
44 import android
.content
.Intent
;
45 import android
.content
.IntentFilter
;
46 import android
.graphics
.Bitmap
;
47 import android
.graphics
.BitmapFactory
;
48 import android
.graphics
.BitmapFactory
.Options
;
49 import android
.graphics
.Point
;
50 import android
.net
.Uri
;
51 import android
.os
.AsyncTask
;
52 import android
.os
.Bundle
;
53 import android
.os
.Handler
;
54 import android
.support
.v4
.app
.DialogFragment
;
55 import android
.support
.v4
.app
.FragmentTransaction
;
56 import android
.util
.Log
;
57 import android
.view
.Display
;
58 import android
.view
.LayoutInflater
;
59 import android
.view
.View
;
60 import android
.view
.View
.OnClickListener
;
61 import android
.view
.ViewGroup
;
62 import android
.webkit
.MimeTypeMap
;
63 import android
.widget
.Button
;
64 import android
.widget
.CheckBox
;
65 import android
.widget
.ImageView
;
66 import android
.widget
.TextView
;
67 import android
.widget
.Toast
;
69 import com
.actionbarsherlock
.app
.SherlockFragment
;
70 import com
.owncloud
.android
.AccountUtils
;
71 import com
.owncloud
.android
.DisplayUtils
;
72 import com
.owncloud
.android
.Log_OC
;
73 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
74 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
75 import com
.owncloud
.android
.datamodel
.OCFile
;
76 import com
.owncloud
.android
.files
.services
.FileDownloader
;
77 import com
.owncloud
.android
.files
.services
.FileObserverService
;
78 import com
.owncloud
.android
.files
.services
.FileUploader
;
79 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
80 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
81 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
82 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
83 import com
.owncloud
.android
.operations
.RemoteOperation
;
84 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
85 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
86 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
87 import com
.owncloud
.android
.operations
.RenameFileOperation
;
88 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
89 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
90 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
91 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
92 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
93 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
95 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
97 import com
.owncloud
.android
.R
;
98 import eu
.alefzero
.webdav
.WebdavClient
;
99 import eu
.alefzero
.webdav
.WebdavUtils
;
102 * This Fragment is used to display the details about a file.
104 * @author Bartek Przybylski
107 public class FileDetailFragment
extends SherlockFragment
implements
108 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
110 public static final String EXTRA_FILE
= "FILE";
111 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
113 private FileDetailFragment
.ContainerActivity mContainerActivity
;
117 private OCFile mFile
;
118 private Account mAccount
;
119 private FileDataStorageManager mStorageManager
;
120 private ImageView mPreview
;
122 private DownloadFinishReceiver mDownloadFinishReceiver
;
123 private UploadFinishReceiver mUploadFinishReceiver
;
125 private Handler mHandler
;
126 private RemoteOperation mLastRemoteOperation
;
127 private DialogFragment mCurrentDialog
;
129 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
130 public static final String FTAG
= "FileDetails";
131 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
135 * Creates an empty details fragment.
137 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
139 public FileDetailFragment() {
142 mStorageManager
= null
;
143 mLayout
= R
.layout
.file_details_empty
;
148 * Creates a details fragment.
150 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
152 * @param fileToDetail An {@link OCFile} to show in the fragment
153 * @param ocAccount An ownCloud account; needed to start downloads
155 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
156 mFile
= fileToDetail
;
157 mAccount
= ocAccount
;
158 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
159 mLayout
= R
.layout
.file_details_empty
;
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
);
180 if(mFile
!= null
&& mAccount
!= null
) {
181 mLayout
= R
.layout
.file_details_fragment
;
185 view
= inflater
.inflate(mLayout
, container
, false
);
188 if (mLayout
== R
.layout
.file_details_fragment
) {
189 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
190 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
191 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
192 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
193 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
194 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
195 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
198 updateFileDetails(false
);
207 public void onAttach(Activity activity
) {
208 super.onAttach(activity
);
210 mContainerActivity
= (ContainerActivity
) activity
;
211 } catch (ClassCastException e
) {
212 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
221 public void onActivityCreated(Bundle savedInstanceState
) {
222 super.onActivityCreated(savedInstanceState
);
223 if (mAccount
!= null
) {
224 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
230 public void onSaveInstanceState(Bundle outState
) {
231 Log_OC
.i(getClass().toString(), "onSaveInstanceState() start");
232 super.onSaveInstanceState(outState
);
233 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
234 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
235 Log_OC
.i(getClass().toString(), "onSaveInstanceState() end");
240 public void onResume() {
243 mDownloadFinishReceiver
= new DownloadFinishReceiver();
244 IntentFilter filter
= new IntentFilter(
245 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
246 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
248 mUploadFinishReceiver
= new UploadFinishReceiver();
249 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
250 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
252 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
256 public void onPause() {
259 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
260 mDownloadFinishReceiver
= null
;
262 getActivity().unregisterReceiver(mUploadFinishReceiver
);
263 mUploadFinishReceiver
= null
;
265 if (mPreview
!= null
) {
271 public View
getView() {
272 return super.getView() == null ? mView
: super.getView();
278 public void onClick(View v
) {
280 case R
.id
.fdDownloadBtn
: {
281 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
282 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
283 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
284 downloaderBinder
.cancel(mAccount
, mFile
);
285 if (mFile
.isDown()) {
288 setButtonsForRemote();
291 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
292 uploaderBinder
.cancel(mAccount
, mFile
);
293 if (!mFile
.fileExists()) {
294 // TODO make something better
295 if (getActivity() instanceof FileDisplayActivity
) {
297 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
298 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
299 transaction
.commit();
300 mContainerActivity
.onFileStateChanged();
302 getActivity().finish();
305 } else if (mFile
.isDown()) {
308 setButtonsForRemote();
312 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
313 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
314 mLastRemoteOperation
.execute(wc
, this, mHandler
);
317 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
318 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
319 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
324 case R
.id
.fdKeepInSync
: {
325 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
326 mFile
.setKeepInSync(cb
.isChecked());
327 mStorageManager
.saveFile(mFile
);
329 /// register the OCFile instance in the observer service to monitor local updates;
330 /// if necessary, the file is download
331 Intent intent
= new Intent(getActivity().getApplicationContext(),
332 FileObserverService
.class);
333 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
335 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
336 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
337 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
338 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
339 Log_OC
.e(TAG
, "starting observer service");
340 getActivity().startService(intent
);
342 if (mFile
.keepInSync()) {
343 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
347 case R
.id
.fdRenameBtn
: {
348 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
349 dialog
.show(getFragmentManager(), "nameeditdialog");
352 case R
.id
.fdRemoveBtn
: {
353 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
354 R
.string
.confirmation_remove_alert
,
355 new String
[]{mFile
.getFileName()},
356 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
357 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
358 R
.string
.common_cancel
);
359 confDialog
.setOnConfirmationListener(this);
360 mCurrentDialog
= confDialog
;
361 mCurrentDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
364 case R
.id
.fdOpenBtn
: {
365 String storagePath
= mFile
.getStoragePath();
366 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
368 Intent i
= new Intent(Intent
.ACTION_VIEW
);
369 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
370 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
373 } catch (Throwable t
) {
374 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
375 boolean toastIt
= true
;
376 String mimeType
= "";
378 Intent i
= new Intent(Intent
.ACTION_VIEW
);
379 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
380 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
381 if (mimeType
!= null
) {
382 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
385 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
387 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
392 } catch (IndexOutOfBoundsException e
) {
393 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
395 } catch (ActivityNotFoundException e
) {
396 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
398 } catch (Throwable th
) {
399 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
403 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
411 Log_OC
.e(TAG
, "Incorrect view clicked!");
414 /* else if (v.getId() == R.id.fdShareBtn) {
415 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
422 public void onConfirmation(String callerTag
) {
423 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
424 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
425 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
428 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
429 mLastRemoteOperation
.execute(wc
, this, mHandler
);
431 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
432 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
435 mCurrentDialog
.dismiss();
436 mCurrentDialog
= null
;
440 public void onNeutral(String callerTag
) {
442 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
444 mFile
.setStoragePath(null
);
445 mStorageManager
.saveFile(mFile
);
446 updateFileDetails(mFile
, mAccount
);
448 mCurrentDialog
.dismiss();
449 mCurrentDialog
= null
;
453 public void onCancel(String callerTag
) {
454 Log_OC
.d(TAG
, "REMOVAL CANCELED");
455 mCurrentDialog
.dismiss();
456 mCurrentDialog
= null
;
461 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
463 * @return True when the fragment was created with the empty layout.
465 public boolean isEmpty() {
466 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
471 * Can be used to get the file that is currently being displayed.
472 * @return The file on the screen.
474 public OCFile
getDisplayedFile(){
479 * Use this method to signal this Activity that it shall update its view.
481 * @param file : An {@link OCFile}
483 public void updateFileDetails(OCFile file
, Account ocAccount
) {
485 if (ocAccount
!= null
&& (
486 mStorageManager
== null
||
487 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
489 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
491 mAccount
= ocAccount
;
492 updateFileDetails(false
);
497 * Updates the view with all relevant details about that file.
499 * TODO Remove parameter when the transferring state of files is kept in database.
501 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
502 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
503 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
506 public void updateFileDetails(boolean transferring
) {
508 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
511 setFilename(mFile
.getFileName());
512 setFiletype(mFile
.getMimetype());
513 setFilesize(mFile
.getFileLength());
514 if(ocVersionSupportsTimeCreated()){
515 setTimeCreated(mFile
.getCreationTimestamp());
518 setTimeModified(mFile
.getModificationTimestamp());
520 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
521 cb
.setChecked(mFile
.keepInSync());
523 // configure UI for depending upon local state of the file
524 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
525 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
526 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
527 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
528 setButtonsForTransferring();
530 } else if (mFile
.isDown()) {
532 if (mFile
.getMimetype().startsWith("image/")) {
533 BitmapLoader bl
= new BitmapLoader();
534 bl
.execute(new String
[]{mFile
.getStoragePath()});
540 // TODO load default preview image; when the local file is removed, the preview remains there
541 setButtonsForRemote();
544 getView().invalidate();
549 * Updates the filename in view
550 * @param filename to set
552 private void setFilename(String filename
) {
553 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
555 tv
.setText(filename
);
559 * Updates the MIME type in view
560 * @param mimetype to set
562 private void setFiletype(String mimetype
) {
563 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
565 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
566 tv
.setText(printableMimetype
);
568 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
570 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
575 * Updates the file size in view
576 * @param filesize in bytes to set
578 private void setFilesize(long filesize
) {
579 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
581 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
585 * Updates the time that the file was created in view
586 * @param milliseconds Unix time to set
588 private void setTimeCreated(long milliseconds
){
589 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
590 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
592 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
593 tv
.setVisibility(View
.VISIBLE
);
594 tvLabel
.setVisibility(View
.VISIBLE
);
599 * Updates the time that the file was last modified
600 * @param milliseconds Unix time to set
602 private void setTimeModified(long milliseconds
){
603 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
605 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
610 * Enables or disables buttons for a file being downloaded
612 private void setButtonsForTransferring() {
614 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
615 downloadButton
.setText(R
.string
.common_cancel
);
616 //downloadButton.setEnabled(false);
618 // let's protect the user from himself ;)
619 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
620 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
621 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
622 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
627 * Enables or disables buttons for a file locally available
629 private void setButtonsForDown() {
631 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
632 downloadButton
.setText(R
.string
.filedetails_sync_file
);
634 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
635 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
636 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
637 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
642 * Enables or disables buttons for a file not locally available
644 private void setButtonsForRemote() {
646 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
647 downloadButton
.setText(R
.string
.filedetails_download
);
649 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
650 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
651 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
652 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
658 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
659 * the time that the file was created. There is a chance that this will
660 * be fixed in future versions. Use this method to check if this version of
661 * ownCloud has this fix.
662 * @return True, if ownCloud the ownCloud version is supporting creation time
664 private boolean ocVersionSupportsTimeCreated(){
665 /*if(mAccount != null){
666 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
667 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
668 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
669 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
678 * Interface to implement by any Activity that includes some instance of FileDetailFragment
680 * @author David A. Velasco
682 public interface ContainerActivity
extends TransferServiceGetter
{
685 * Callback method invoked when the detail fragment wants to notice its container
686 * activity about a relevant state the file shown by the fragment.
688 * Added to notify to FileDisplayActivity about the need of refresh the files list.
690 * Currently called when:
691 * - a download is started;
692 * - a rename is completed;
693 * - a deletion is completed;
694 * - the 'inSync' flag is changed;
696 public void onFileStateChanged();
702 * Once the file download has finished -> update view
703 * @author Bartek Przybylski
705 private class DownloadFinishReceiver
extends BroadcastReceiver
{
707 public void onReceive(Context context
, Intent intent
) {
708 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
710 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
711 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
712 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
713 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
714 if (downloadWasFine
) {
715 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
717 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
725 * Once the file upload has finished -> update view
727 * Being notified about the finish of an upload is necessary for the next sequence:
728 * 1. Upload a big file.
729 * 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
730 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
731 * 3. Click the file in the list to see its details.
732 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
734 private class UploadFinishReceiver
extends BroadcastReceiver
{
736 public void onReceive(Context context
, Intent intent
) {
737 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
739 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
740 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
741 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
742 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
743 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
746 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
748 if (renamedInUpload
) {
749 String newName
= (new File(uploadRemotePath
)).getName();
750 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
753 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
754 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
761 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
762 @SuppressWarnings("unused")
763 private class ShareRunnable
implements Runnable
{
764 private String mPath
;
766 public ShareRunnable(String path
) {
771 AccountManager am
= AccountManager
.get(getActivity());
772 Account account
= AccountUtils
.getCurrentOwnCloudAccount(getActivity());
773 OwnCloudVersion ocv
= new OwnCloudVersion(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
));
774 String url
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + AccountUtils
.getWebdavPath(ocv
);
776 Log_OC
.d("share", "sharing for version " + ocv
.toString());
778 if (ocv
.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
779 String APPS_PATH
= "/apps/files_sharing/";
780 String SHARE_PATH
= "ajax/share.php";
782 String SHARED_PATH
= "/apps/files_sharing/get.php?token=";
784 final String WEBDAV_SCRIPT
= "webdav.php";
785 final String WEBDAV_FILES_LOCATION
= "/files/";
787 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(account
, getActivity().getApplicationContext());
788 HttpConnectionManagerParams params
= new HttpConnectionManagerParams();
789 params
.setMaxConnectionsPerHost(wc
.getHostConfiguration(), 5);
791 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
792 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
794 PostMethod post
= new PostMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + APPS_PATH
+ SHARE_PATH
);
796 post
.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
797 post
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
798 List
<NameValuePair
> formparams
= new ArrayList
<NameValuePair
>();
799 Log_OC
.d("share", mPath
+"");
800 formparams
.add(new BasicNameValuePair("sources",mPath
));
801 formparams
.add(new BasicNameValuePair("uid_shared_with", "public"));
802 formparams
.add(new BasicNameValuePair("permissions", "0"));
803 post
.setRequestEntity(new StringRequestEntity(URLEncodedUtils
.format(formparams
, HTTP
.UTF_8
)));
807 PropFindMethod find
= new PropFindMethod(url
+"/");
808 find
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
809 Log_OC
.d("sharer", ""+ url
+"/");
811 for (org
.apache
.commons
.httpclient
.Header a
: find
.getRequestHeaders()) {
812 Log_OC
.d("sharer-h", a
.getName() + ":"+a
.getValue());
815 int status2
= wc
.executeMethod(find
);
817 Log_OC
.d("sharer", "propstatus "+status2
);
819 GetMethod get
= new GetMethod(am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + "/");
820 get
.addRequestHeader("Referer", am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
));
822 status2
= wc
.executeMethod(get
);
824 Log_OC
.d("sharer", "getstatus "+status2
);
825 Log_OC
.d("sharer", "" + get
.getResponseBodyAsString());
827 for (org
.apache
.commons
.httpclient
.Header a
: get
.getResponseHeaders()) {
828 Log_OC
.d("sharer", a
.getName() + ":"+a
.getValue());
831 status
= wc
.executeMethod(post
);
832 for (org
.apache
.commons
.httpclient
.Header a
: post
.getRequestHeaders()) {
833 Log_OC
.d("sharer-h", a
.getName() + ":"+a
.getValue());
835 for (org
.apache
.commons
.httpclient
.Header a
: post
.getResponseHeaders()) {
836 Log_OC
.d("sharer", a
.getName() + ":"+a
.getValue());
838 String resp
= post
.getResponseBodyAsString();
839 Log_OC
.d("share", ""+post
.getURI().toString());
840 Log_OC
.d("share", "returned status " + status
);
841 Log_OC
.d("share", " " +resp
);
843 if(status
!= HttpStatus
.SC_OK
||resp
== null
|| resp
.equals("") || resp
.startsWith("false")) {
847 JSONObject jsonObject
= new JSONObject (resp
);
848 String jsonStatus
= jsonObject
.getString("status");
849 if(!jsonStatus
.equals("success")) throw new Exception("Error while sharing file status != success");
851 String token
= jsonObject
.getString("data");
852 String uri
= am
.getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
) + SHARED_PATH
+ token
;
853 Log_OC
.d("Actions:shareFile ok", "url: " + uri
);
855 } catch (Exception e
) {
859 } else if (ocv
.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
865 public void onDismiss(EditNameDialog dialog
) {
866 if (dialog
.getResult()) {
867 String newFilename
= dialog
.getNewFilename();
868 Log_OC
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
869 mLastRemoteOperation
= new RenameFileOperation( mFile
,
872 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
873 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getSherlockActivity().getApplicationContext());
874 mLastRemoteOperation
.execute(wc
, this, mHandler
);
875 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
876 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
881 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
882 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
884 protected Bitmap
doInBackground(String
... params
) {
885 Bitmap result
= null
;
886 if (params
.length
!= 1) return result
;
887 String storagePath
= params
[0];
890 BitmapFactory
.Options options
= new Options();
891 options
.inScaled
= true
;
892 options
.inPurgeable
= true
;
893 options
.inJustDecodeBounds
= true
;
894 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
895 options
.inPreferQualityOverSpeed
= false
;
897 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
898 options
.inMutable
= false
;
901 result
= BitmapFactory
.decodeFile(storagePath
, options
);
902 options
.inJustDecodeBounds
= false
;
904 int width
= options
.outWidth
;
905 int height
= options
.outHeight
;
907 if (width
>= 2048 || height
>= 2048) {
908 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
909 options
.inSampleSize
= scale
;
911 Display display
= getActivity().getWindowManager().getDefaultDisplay();
912 Point size
= new Point();
914 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
915 display
.getSize(size
);
916 screenwidth
= size
.x
;
918 screenwidth
= display
.getWidth();
921 Log_OC
.e("ASD", "W " + width
+ " SW " + screenwidth
);
923 if (width
> screenwidth
) {
924 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
925 options
.inSampleSize
= scale
;
928 result
= BitmapFactory
.decodeFile(storagePath
, options
);
930 Log_OC
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
932 } catch (OutOfMemoryError e
) {
934 Log_OC
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
936 } catch (NoSuchFieldError e
) {
938 Log_OC
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
940 } catch (Throwable t
) {
942 Log_OC
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
947 protected void onPostExecute(Bitmap result
) {
948 if (result
!= null
&& mPreview
!= null
) {
949 mPreview
.setImageBitmap(result
);
959 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
960 if (operation
.equals(mLastRemoteOperation
)) {
961 if (operation
instanceof RemoveFileOperation
) {
962 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
964 } else if (operation
instanceof RenameFileOperation
) {
965 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
967 } else if (operation
instanceof SynchronizeFileOperation
) {
968 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
974 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
975 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
976 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
978 if (result
.isSuccess()) {
979 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
981 if (inDisplayActivity
) {
983 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
984 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
985 transaction
.commit();
986 mContainerActivity
.onFileStateChanged();
988 getActivity().finish();
992 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
994 if (result
.isSslRecoverableException()) {
995 // TODO show the SSL warning dialog
1000 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
1001 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1002 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1004 if (result
.isSuccess()) {
1005 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
1006 mContainerActivity
.onFileStateChanged();
1009 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
1010 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
1012 // TODO throw again the new rename dialog
1014 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
1016 if (result
.isSslRecoverableException()) {
1017 // TODO show the SSL warning dialog
1023 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1024 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1025 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1027 if (!result
.isSuccess()) {
1028 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1029 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1030 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1031 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1035 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1039 if (mFile
.isDown()) {
1040 setButtonsForDown();
1043 setButtonsForRemote();
1047 if (operation
.transferWasRequested()) {
1048 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1049 // checking the service to see if the file is downloading results in FALSE
1051 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1053 if (mFile
.isDown()) {
1054 setButtonsForDown();
1057 setButtonsForRemote();