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
;
23 import org
.apache
.commons
.httpclient
.Credentials
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.annotation
.SuppressLint
;
28 import android
.app
.Activity
;
29 import android
.content
.ActivityNotFoundException
;
30 import android
.content
.BroadcastReceiver
;
31 import android
.content
.Context
;
32 import android
.content
.Intent
;
33 import android
.content
.IntentFilter
;
34 import android
.graphics
.Bitmap
;
35 import android
.graphics
.BitmapFactory
;
36 import android
.graphics
.BitmapFactory
.Options
;
37 import android
.graphics
.Point
;
38 import android
.net
.Uri
;
39 import android
.os
.AsyncTask
;
40 import android
.os
.Bundle
;
41 import android
.os
.Handler
;
42 import android
.support
.v4
.app
.DialogFragment
;
43 import android
.support
.v4
.app
.FragmentTransaction
;
44 import android
.util
.Log
;
45 import android
.view
.Display
;
46 import android
.view
.LayoutInflater
;
47 import android
.view
.View
;
48 import android
.view
.View
.OnClickListener
;
49 import android
.view
.ViewGroup
;
50 import android
.webkit
.MimeTypeMap
;
51 import android
.widget
.Button
;
52 import android
.widget
.CheckBox
;
53 import android
.widget
.ImageView
;
54 import android
.widget
.TextView
;
55 import android
.widget
.Toast
;
57 import com
.actionbarsherlock
.app
.SherlockFragment
;
58 import com
.owncloud
.android
.DisplayUtils
;
59 import com
.owncloud
.android
.authentication
.AccountAuthenticator
;
60 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
61 import com
.owncloud
.android
.datamodel
.OCFile
;
62 import com
.owncloud
.android
.files
.services
.FileDownloader
;
63 import com
.owncloud
.android
.files
.services
.FileObserverService
;
64 import com
.owncloud
.android
.files
.services
.FileUploader
;
65 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
66 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
67 import com
.owncloud
.android
.network
.BearerCredentials
;
68 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
69 import com
.owncloud
.android
.operations
.RemoteOperation
;
70 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
71 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
72 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
73 import com
.owncloud
.android
.operations
.RenameFileOperation
;
74 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
75 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
76 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
77 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
78 import com
.owncloud
.android
.ui
.activity
.TransferServiceGetter
;
79 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
80 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
82 import com
.owncloud
.android
.R
;
83 import eu
.alefzero
.webdav
.WebdavUtils
;
86 * This Fragment is used to display the details about a file.
88 * @author Bartek Przybylski
91 public class FileDetailFragment
extends SherlockFragment
implements
92 OnClickListener
, ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
{
94 public static final String EXTRA_FILE
= "FILE";
95 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
97 private FileDetailFragment
.ContainerActivity mContainerActivity
;
101 private OCFile mFile
;
102 private Account mAccount
;
103 private FileDataStorageManager mStorageManager
;
104 private ImageView mPreview
;
106 private DownloadFinishReceiver mDownloadFinishReceiver
;
107 private UploadFinishReceiver mUploadFinishReceiver
;
109 private Handler mHandler
;
110 private RemoteOperation mLastRemoteOperation
;
111 private DialogFragment mCurrentDialog
;
113 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
114 public static final String FTAG
= "FileDetails";
115 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
119 * Creates an empty details fragment.
121 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
123 public FileDetailFragment() {
126 mStorageManager
= null
;
127 mLayout
= R
.layout
.file_details_empty
;
132 * Creates a details fragment.
134 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
136 * @param fileToDetail An {@link OCFile} to show in the fragment
137 * @param ocAccount An ownCloud account; needed to start downloads
139 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
140 mFile
= fileToDetail
;
141 mAccount
= ocAccount
;
142 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
143 mLayout
= R
.layout
.file_details_empty
;
148 public void onCreate(Bundle savedInstanceState
) {
149 super.onCreate(savedInstanceState
);
150 mHandler
= new Handler();
155 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
156 Bundle savedInstanceState
) {
157 super.onCreateView(inflater
, container
, savedInstanceState
);
159 if (savedInstanceState
!= null
) {
160 mFile
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_FILE
);
161 mAccount
= savedInstanceState
.getParcelable(FileDetailFragment
.EXTRA_ACCOUNT
);
164 if(mFile
!= null
&& mAccount
!= null
) {
165 mLayout
= R
.layout
.file_details_fragment
;
169 view
= inflater
.inflate(mLayout
, container
, false
);
172 if (mLayout
== R
.layout
.file_details_fragment
) {
173 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
174 mView
.findViewById(R
.id
.fdRenameBtn
).setOnClickListener(this);
175 mView
.findViewById(R
.id
.fdDownloadBtn
).setOnClickListener(this);
176 mView
.findViewById(R
.id
.fdOpenBtn
).setOnClickListener(this);
177 mView
.findViewById(R
.id
.fdRemoveBtn
).setOnClickListener(this);
178 //mView.findViewById(R.id.fdShareBtn).setOnClickListener(this);
179 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
182 updateFileDetails(false
);
191 public void onAttach(Activity activity
) {
192 super.onAttach(activity
);
194 mContainerActivity
= (ContainerActivity
) activity
;
195 } catch (ClassCastException e
) {
196 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
205 public void onActivityCreated(Bundle savedInstanceState
) {
206 super.onActivityCreated(savedInstanceState
);
207 if (mAccount
!= null
) {
208 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());;
214 public void onSaveInstanceState(Bundle outState
) {
215 Log
.i(getClass().toString(), "onSaveInstanceState() start");
216 super.onSaveInstanceState(outState
);
217 outState
.putParcelable(FileDetailFragment
.EXTRA_FILE
, mFile
);
218 outState
.putParcelable(FileDetailFragment
.EXTRA_ACCOUNT
, mAccount
);
219 Log
.i(getClass().toString(), "onSaveInstanceState() end");
224 public void onResume() {
227 mDownloadFinishReceiver
= new DownloadFinishReceiver();
228 IntentFilter filter
= new IntentFilter(
229 FileDownloader
.DOWNLOAD_FINISH_MESSAGE
);
230 getActivity().registerReceiver(mDownloadFinishReceiver
, filter
);
232 mUploadFinishReceiver
= new UploadFinishReceiver();
233 filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
234 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
236 mPreview
= (ImageView
)mView
.findViewById(R
.id
.fdPreview
);
240 public void onPause() {
243 getActivity().unregisterReceiver(mDownloadFinishReceiver
);
244 mDownloadFinishReceiver
= null
;
246 getActivity().unregisterReceiver(mUploadFinishReceiver
);
247 mUploadFinishReceiver
= null
;
249 if (mPreview
!= null
) {
255 public View
getView() {
256 return super.getView() == null ? mView
: super.getView();
262 public void onClick(View v
) {
264 case R
.id
.fdDownloadBtn
: {
265 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
266 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
267 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
268 downloaderBinder
.cancel(mAccount
, mFile
);
269 if (mFile
.isDown()) {
272 setButtonsForRemote();
275 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
276 uploaderBinder
.cancel(mAccount
, mFile
);
277 if (!mFile
.fileExists()) {
278 // TODO make something better
279 if (getActivity() instanceof FileDisplayActivity
) {
281 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
282 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
283 transaction
.commit();
284 mContainerActivity
.onFileStateChanged();
286 getActivity().finish();
289 } else if (mFile
.isDown()) {
292 setButtonsForRemote();
296 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
297 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
300 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
301 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
302 setButtonsForTransferring(); // disable button immediately, although the synchronization does not result in a file transference
307 case R
.id
.fdKeepInSync
: {
308 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
309 mFile
.setKeepInSync(cb
.isChecked());
310 mStorageManager
.saveFile(mFile
);
312 /// register the OCFile instance in the observer service to monitor local updates;
313 /// if necessary, the file is download
314 Intent intent
= new Intent(getActivity().getApplicationContext(),
315 FileObserverService
.class);
316 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
318 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
319 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
320 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
321 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
322 Log
.e(TAG
, "starting observer service");
323 getActivity().startService(intent
);
325 if (mFile
.keepInSync()) {
326 onClick(getView().findViewById(R
.id
.fdDownloadBtn
)); // force an immediate synchronization
330 case R
.id
.fdRenameBtn
: {
331 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), mFile
.getFileName(), this);
332 dialog
.show(getFragmentManager(), "nameeditdialog");
335 case R
.id
.fdRemoveBtn
: {
336 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
337 R
.string
.confirmation_remove_alert
,
338 new String
[]{mFile
.getFileName()},
339 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
340 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
341 R
.string
.common_cancel
);
342 confDialog
.setOnConfirmationListener(this);
343 mCurrentDialog
= confDialog
;
344 mCurrentDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
347 case R
.id
.fdOpenBtn
: {
348 String storagePath
= mFile
.getStoragePath();
349 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
351 Intent i
= new Intent(Intent
.ACTION_VIEW
);
352 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
353 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
356 } catch (Throwable t
) {
357 Log
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
358 boolean toastIt
= true
;
359 String mimeType
= "";
361 Intent i
= new Intent(Intent
.ACTION_VIEW
);
362 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
363 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
364 if (mimeType
!= null
) {
365 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
368 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
370 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
375 } catch (IndexOutOfBoundsException e
) {
376 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
378 } catch (ActivityNotFoundException e
) {
379 Log
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
381 } catch (Throwable th
) {
382 Log
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
386 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
394 Log
.e(TAG
, "Incorrect view clicked!");
397 /* else if (v.getId() == R.id.fdShareBtn) {
398 Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
405 public void onConfirmation(String callerTag
) {
406 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
407 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
408 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
411 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
412 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
413 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
416 mCurrentDialog
.dismiss();
417 mCurrentDialog
= null
;
421 public void onNeutral(String callerTag
) {
423 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
425 mFile
.setStoragePath(null
);
426 mStorageManager
.saveFile(mFile
);
427 updateFileDetails(mFile
, mAccount
);
429 mCurrentDialog
.dismiss();
430 mCurrentDialog
= null
;
434 public void onCancel(String callerTag
) {
435 Log
.d(TAG
, "REMOVAL CANCELED");
436 mCurrentDialog
.dismiss();
437 mCurrentDialog
= null
;
442 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
444 * @return True when the fragment was created with the empty layout.
446 public boolean isEmpty() {
447 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
452 * Can be used to get the file that is currently being displayed.
453 * @return The file on the screen.
455 public OCFile
getDisplayedFile(){
460 * Use this method to signal this Activity that it shall update its view.
462 * @param file : An {@link OCFile}
464 public void updateFileDetails(OCFile file
, Account ocAccount
) {
466 if (ocAccount
!= null
&& (
467 mStorageManager
== null
||
468 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
470 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
472 mAccount
= ocAccount
;
473 updateFileDetails(false
);
478 * Updates the view with all relevant details about that file.
480 * TODO Remove parameter when the transferring state of files is kept in database.
482 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
483 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
484 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
487 public void updateFileDetails(boolean transferring
) {
489 if (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
) {
492 setFilename(mFile
.getFileName());
493 setFiletype(mFile
.getMimetype());
494 setFilesize(mFile
.getFileLength());
495 if(ocVersionSupportsTimeCreated()){
496 setTimeCreated(mFile
.getCreationTimestamp());
499 setTimeModified(mFile
.getModificationTimestamp());
501 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
502 cb
.setChecked(mFile
.keepInSync());
504 // configure UI for depending upon local state of the file
505 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
506 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
507 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
508 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
509 setButtonsForTransferring();
511 } else if (mFile
.isDown()) {
513 if (mFile
.getMimetype().startsWith("image/")) {
514 BitmapLoader bl
= new BitmapLoader();
515 bl
.execute(new String
[]{mFile
.getStoragePath()});
521 // TODO load default preview image; when the local file is removed, the preview remains there
522 setButtonsForRemote();
525 getView().invalidate();
530 * Updates the filename in view
531 * @param filename to set
533 private void setFilename(String filename
) {
534 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
536 tv
.setText(filename
);
540 * Updates the MIME type in view
541 * @param mimetype to set
543 private void setFiletype(String mimetype
) {
544 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
546 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
547 tv
.setText(printableMimetype
);
549 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
551 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
556 * Updates the file size in view
557 * @param filesize in bytes to set
559 private void setFilesize(long filesize
) {
560 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
562 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
566 * Updates the time that the file was created in view
567 * @param milliseconds Unix time to set
569 private void setTimeCreated(long milliseconds
){
570 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
571 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
573 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
574 tv
.setVisibility(View
.VISIBLE
);
575 tvLabel
.setVisibility(View
.VISIBLE
);
580 * Updates the time that the file was last modified
581 * @param milliseconds Unix time to set
583 private void setTimeModified(long milliseconds
){
584 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
586 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
591 * Enables or disables buttons for a file being downloaded
593 private void setButtonsForTransferring() {
595 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
596 downloadButton
.setText(R
.string
.common_cancel
);
597 //downloadButton.setEnabled(false);
599 // let's protect the user from himself ;)
600 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
601 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(false
);
602 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(false
);
603 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
608 * Enables or disables buttons for a file locally available
610 private void setButtonsForDown() {
612 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
613 downloadButton
.setText(R
.string
.filedetails_sync_file
);
615 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(true
);
616 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
617 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
618 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
623 * Enables or disables buttons for a file not locally available
625 private void setButtonsForRemote() {
627 Button downloadButton
= (Button
) getView().findViewById(R
.id
.fdDownloadBtn
);
628 downloadButton
.setText(R
.string
.filedetails_download
);
630 ((Button
) getView().findViewById(R
.id
.fdOpenBtn
)).setEnabled(false
);
631 ((Button
) getView().findViewById(R
.id
.fdRenameBtn
)).setEnabled(true
);
632 ((Button
) getView().findViewById(R
.id
.fdRemoveBtn
)).setEnabled(true
);
633 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
639 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
640 * the time that the file was created. There is a chance that this will
641 * be fixed in future versions. Use this method to check if this version of
642 * ownCloud has this fix.
643 * @return True, if ownCloud the ownCloud version is supporting creation time
645 private boolean ocVersionSupportsTimeCreated(){
646 /*if(mAccount != null){
647 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
648 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
649 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
650 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
659 * Interface to implement by any Activity that includes some instance of FileDetailFragment
661 * @author David A. Velasco
663 public interface ContainerActivity
extends TransferServiceGetter
{
666 * Callback method invoked when the detail fragment wants to notice its container
667 * activity about a relevant state the file shown by the fragment.
669 * Added to notify to FileDisplayActivity about the need of refresh the files list.
671 * Currently called when:
672 * - a download is started;
673 * - a rename is completed;
674 * - a deletion is completed;
675 * - the 'inSync' flag is changed;
677 public void onFileStateChanged();
683 * Once the file download has finished -> update view
684 * @author Bartek Przybylski
686 private class DownloadFinishReceiver
extends BroadcastReceiver
{
688 public void onReceive(Context context
, Intent intent
) {
689 String accountName
= intent
.getStringExtra(FileDownloader
.ACCOUNT_NAME
);
691 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
692 boolean downloadWasFine
= intent
.getBooleanExtra(FileDownloader
.EXTRA_DOWNLOAD_RESULT
, false
);
693 String downloadedRemotePath
= intent
.getStringExtra(FileDownloader
.EXTRA_REMOTE_PATH
);
694 if (mFile
.getRemotePath().equals(downloadedRemotePath
)) {
695 if (downloadWasFine
) {
696 mFile
= mStorageManager
.getFileByPath(downloadedRemotePath
);
698 updateFileDetails(false
); // it updates the buttons; must be called although !downloadWasFine
706 * Once the file upload has finished -> update view
708 * Being notified about the finish of an upload is necessary for the next sequence:
709 * 1. Upload a big file.
710 * 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
711 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
712 * 3. Click the file in the list to see its details.
713 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
715 private class UploadFinishReceiver
extends BroadcastReceiver
{
717 public void onReceive(Context context
, Intent intent
) {
718 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
720 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
721 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
722 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
723 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
724 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
727 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
729 if (renamedInUpload
) {
730 String newName
= (new File(uploadRemotePath
)).getName();
731 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
734 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
735 updateFileDetails(false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
742 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
744 @SuppressWarnings("unused")
745 private class ShareRunnable implements Runnable {
746 private String mPath;
748 public ShareRunnable(String path) {
753 AccountManager am = AccountManager.get(getActivity());
754 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
755 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
756 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
758 Log.d("share", "sharing for version " + ocv.toString());
760 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
761 String APPS_PATH = "/apps/files_sharing/";
762 String SHARE_PATH = "ajax/share.php";
764 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
766 final String WEBDAV_SCRIPT = "webdav.php";
767 final String WEBDAV_FILES_LOCATION = "/files/";
769 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
770 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
771 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
773 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
774 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
776 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
778 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
779 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
780 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
781 Log.d("share", mPath+"");
782 formparams.add(new BasicNameValuePair("sources",mPath));
783 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
784 formparams.add(new BasicNameValuePair("permissions", "0"));
785 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
789 PropFindMethod find = new PropFindMethod(url+"/");
790 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
791 Log.d("sharer", ""+ url+"/");
793 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
794 Log.d("sharer-h", a.getName() + ":"+a.getValue());
797 int status2 = wc.executeMethod(find);
799 Log.d("sharer", "propstatus "+status2);
801 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
802 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
804 status2 = wc.executeMethod(get);
806 Log.d("sharer", "getstatus "+status2);
807 Log.d("sharer", "" + get.getResponseBodyAsString());
809 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
810 Log.d("sharer", a.getName() + ":"+a.getValue());
813 status = wc.executeMethod(post);
814 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
815 Log.d("sharer-h", a.getName() + ":"+a.getValue());
817 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
818 Log.d("sharer", a.getName() + ":"+a.getValue());
820 String resp = post.getResponseBodyAsString();
821 Log.d("share", ""+post.getURI().toString());
822 Log.d("share", "returned status " + status);
823 Log.d("share", " " +resp);
825 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
829 JSONObject jsonObject = new JSONObject (resp);
830 String jsonStatus = jsonObject.getString("status");
831 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
833 String token = jsonObject.getString("data");
834 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
835 Log.d("Actions:shareFile ok", "url: " + uri);
837 } catch (Exception e) {
841 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {
848 public void onDismiss(EditNameDialog dialog
) {
849 if (dialog
.getResult()) {
850 String newFilename
= dialog
.getNewFilename();
851 Log
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
852 mLastRemoteOperation
= new RenameFileOperation( mFile
,
855 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
856 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
857 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
858 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
863 class BitmapLoader
extends AsyncTask
<String
, Void
, Bitmap
> {
864 @SuppressLint({ "NewApi", "NewApi", "NewApi" }) // to avoid Lint errors since Android SDK r20
866 protected Bitmap
doInBackground(String
... params
) {
867 Bitmap result
= null
;
868 if (params
.length
!= 1) return result
;
869 String storagePath
= params
[0];
872 BitmapFactory
.Options options
= new Options();
873 options
.inScaled
= true
;
874 options
.inPurgeable
= true
;
875 options
.inJustDecodeBounds
= true
;
876 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.GINGERBREAD_MR1
) {
877 options
.inPreferQualityOverSpeed
= false
;
879 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB
) {
880 options
.inMutable
= false
;
883 result
= BitmapFactory
.decodeFile(storagePath
, options
);
884 options
.inJustDecodeBounds
= false
;
886 int width
= options
.outWidth
;
887 int height
= options
.outHeight
;
889 if (width
>= 2048 || height
>= 2048) {
890 scale
= (int) Math
.ceil((Math
.ceil(Math
.max(height
, width
) / 2048.)));
891 options
.inSampleSize
= scale
;
893 Display display
= getActivity().getWindowManager().getDefaultDisplay();
894 Point size
= new Point();
896 if (android
.os
.Build
.VERSION
.SDK_INT
>= android
.os
.Build
.VERSION_CODES
.HONEYCOMB_MR2
) {
897 display
.getSize(size
);
898 screenwidth
= size
.x
;
900 screenwidth
= display
.getWidth();
903 Log
.e("ASD", "W " + width
+ " SW " + screenwidth
);
905 if (width
> screenwidth
) {
906 scale
= (int) Math
.ceil((float)width
/ screenwidth
);
907 options
.inSampleSize
= scale
;
910 result
= BitmapFactory
.decodeFile(storagePath
, options
);
912 Log
.e("ASD", "W " + options
.outWidth
+ " SW " + options
.outHeight
);
914 } catch (OutOfMemoryError e
) {
916 Log
.e(TAG
, "Out of memory occured for file with size " + storagePath
);
918 } catch (NoSuchFieldError e
) {
920 Log
.e(TAG
, "Error from access to unexisting field despite protection " + storagePath
);
922 } catch (Throwable t
) {
924 Log
.e(TAG
, "Unexpected error while creating image preview " + storagePath
, t
);
929 protected void onPostExecute(Bitmap result
) {
930 if (result
!= null
&& mPreview
!= null
) {
931 mPreview
.setImageBitmap(result
);
941 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
942 if (operation
instanceof RemoveFileOperation
) {
943 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
945 } else if (operation
instanceof RenameFileOperation
) {
946 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
948 } else if (operation
instanceof SynchronizeFileOperation
) {
949 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
954 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
955 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
956 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
958 if (result
.isSuccess()) {
959 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
961 if (inDisplayActivity
) {
963 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
964 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
965 transaction
.commit();
966 mContainerActivity
.onFileStateChanged();
968 getActivity().finish();
972 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
974 if (result
.isSslRecoverableException()) {
975 // TODO show the SSL warning dialog
980 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
981 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
982 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
984 if (result
.isSuccess()) {
985 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
986 mContainerActivity
.onFileStateChanged();
989 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
990 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
992 // TODO throw again the new rename dialog
994 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
996 if (result
.isSslRecoverableException()) {
997 // TODO show the SSL warning dialog
1003 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
1004 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
1005 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
1007 if (!result
.isSuccess()) {
1008 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
1009 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
1010 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
1011 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
1015 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
1019 if (mFile
.isDown()) {
1020 setButtonsForDown();
1023 setButtonsForRemote();
1027 if (operation
.transferWasRequested()) {
1028 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
1029 // checking the service to see if the file is downloading results in FALSE
1031 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
1033 if (mFile
.isDown()) {
1034 setButtonsForDown();
1037 setButtonsForRemote();