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 version 2,
7 * as published by the Free Software Foundation.
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
.lang
.ref
.WeakReference
;
22 import java
.util
.ArrayList
;
23 import java
.util
.List
;
25 import android
.accounts
.Account
;
26 import android
.app
.Activity
;
27 import android
.content
.ActivityNotFoundException
;
28 import android
.content
.BroadcastReceiver
;
29 import android
.content
.Context
;
30 import android
.content
.Intent
;
31 import android
.content
.IntentFilter
;
32 import android
.net
.Uri
;
33 import android
.os
.Bundle
;
34 import android
.os
.Handler
;
35 import android
.support
.v4
.app
.FragmentTransaction
;
36 import android
.view
.LayoutInflater
;
37 import android
.view
.View
;
38 import android
.view
.View
.OnClickListener
;
39 import android
.view
.ViewGroup
;
40 import android
.webkit
.MimeTypeMap
;
41 import android
.widget
.CheckBox
;
42 import android
.widget
.ImageView
;
43 import android
.widget
.ProgressBar
;
44 import android
.widget
.TextView
;
45 import android
.widget
.Toast
;
47 import com
.actionbarsherlock
.app
.SherlockFragment
;
48 import com
.actionbarsherlock
.view
.Menu
;
49 import com
.actionbarsherlock
.view
.MenuInflater
;
50 import com
.actionbarsherlock
.view
.MenuItem
;
51 import com
.owncloud
.android
.DisplayUtils
;
52 import com
.owncloud
.android
.Log_OC
;
53 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
54 import com
.owncloud
.android
.datamodel
.OCFile
;
55 import com
.owncloud
.android
.files
.services
.FileObserverService
;
56 import com
.owncloud
.android
.files
.services
.FileUploader
;
57 import com
.owncloud
.android
.files
.services
.FileDownloader
.FileDownloaderBinder
;
58 import com
.owncloud
.android
.files
.services
.FileUploader
.FileUploaderBinder
;
59 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
60 import com
.owncloud
.android
.operations
.RemoteOperation
;
61 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
62 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
63 import com
.owncloud
.android
.operations
.RemoveFileOperation
;
64 import com
.owncloud
.android
.operations
.RenameFileOperation
;
65 import com
.owncloud
.android
.operations
.SynchronizeFileOperation
;
66 import com
.owncloud
.android
.ui
.activity
.ConflictsResolveActivity
;
67 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
68 import com
.owncloud
.android
.ui
.activity
.FileDetailActivity
;
69 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
70 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
;
71 import com
.owncloud
.android
.ui
.dialog
.EditNameDialog
.EditNameDialogListener
;
73 import com
.owncloud
.android
.R
;
75 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
76 import eu
.alefzero
.webdav
.WebdavUtils
;
79 * This Fragment is used to display the details about a file.
81 * @author Bartek Przybylski
82 * @author David A. Velasco
84 public class FileDetailFragment
extends SherlockFragment
implements
86 ConfirmationDialogFragment
.ConfirmationDialogFragmentListener
, OnRemoteOperationListener
, EditNameDialogListener
,
89 private FileFragment
.ContainerActivity mContainerActivity
;
94 private Account mAccount
;
95 private FileDataStorageManager mStorageManager
;
97 private UploadFinishReceiver mUploadFinishReceiver
;
98 public ProgressListener mProgressListener
;
100 private Handler mHandler
;
101 private RemoteOperation mLastRemoteOperation
;
103 private static final String TAG
= FileDetailFragment
.class.getSimpleName();
104 public static final String FTAG
= "FileDetails";
105 public static final String FTAG_CONFIRMATION
= "REMOVE_CONFIRMATION_FRAGMENT";
109 * Creates an empty details fragment.
111 * It's necessary to keep a public constructor without parameters; the system uses it when tries to reinstantiate a fragment automatically.
113 public FileDetailFragment() {
116 mStorageManager
= null
;
117 mLayout
= R
.layout
.file_details_empty
;
118 mProgressListener
= null
;
122 * Creates a details fragment.
124 * When 'fileToDetail' or 'ocAccount' are null, creates a dummy layout (to use when a file wasn't tapped before).
126 * @param fileToDetail An {@link OCFile} to show in the fragment
127 * @param ocAccount An ownCloud account; needed to start downloads
129 public FileDetailFragment(OCFile fileToDetail
, Account ocAccount
) {
130 mFile
= fileToDetail
;
131 mAccount
= ocAccount
;
132 mStorageManager
= null
; // we need a context to init this; the container activity is not available yet at this moment
133 mLayout
= R
.layout
.file_details_empty
;
134 mProgressListener
= null
;
139 public void onCreate(Bundle savedInstanceState
) {
140 super.onCreate(savedInstanceState
);
141 mHandler
= new Handler();
142 setHasOptionsMenu(true
);
147 public View
onCreateView(LayoutInflater inflater
, ViewGroup container
,
148 Bundle savedInstanceState
) {
149 super.onCreateView(inflater
, container
, savedInstanceState
);
151 if (savedInstanceState
!= null
) {
152 mFile
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_FILE
);
153 mAccount
= savedInstanceState
.getParcelable(FileActivity
.EXTRA_ACCOUNT
);
156 if(mFile
!= null
&& mAccount
!= null
) {
157 mLayout
= R
.layout
.file_details_fragment
;
161 view
= inflater
.inflate(mLayout
, container
, false
);
164 if (mLayout
== R
.layout
.file_details_fragment
) {
165 mView
.findViewById(R
.id
.fdKeepInSync
).setOnClickListener(this);
166 ProgressBar progressBar
= (ProgressBar
)mView
.findViewById(R
.id
.fdProgressBar
);
167 mProgressListener
= new ProgressListener(progressBar
);
168 mView
.findViewById(R
.id
.fdCancelBtn
).setOnClickListener(this);
171 updateFileDetails(false
, false
);
179 public void onAttach(Activity activity
) {
180 super.onAttach(activity
);
182 mContainerActivity
= (ContainerActivity
) activity
;
184 } catch (ClassCastException e
) {
185 throw new ClassCastException(activity
.toString() + " must implement " + FileDetailFragment
.ContainerActivity
.class.getSimpleName());
194 public void onActivityCreated(Bundle savedInstanceState
) {
195 super.onActivityCreated(savedInstanceState
);
196 if (mAccount
!= null
) {
197 mStorageManager
= new FileDataStorageManager(mAccount
, getActivity().getApplicationContext().getContentResolver());
203 public void onSaveInstanceState(Bundle outState
) {
204 super.onSaveInstanceState(outState
);
205 outState
.putParcelable(FileActivity
.EXTRA_FILE
, mFile
);
206 outState
.putParcelable(FileActivity
.EXTRA_ACCOUNT
, mAccount
);
210 public void onStart() {
212 listenForTransferProgress();
216 public void onResume() {
218 mUploadFinishReceiver
= new UploadFinishReceiver();
219 IntentFilter filter
= new IntentFilter(FileUploader
.UPLOAD_FINISH_MESSAGE
);
220 getActivity().registerReceiver(mUploadFinishReceiver
, filter
);
226 public void onPause() {
228 if (mUploadFinishReceiver
!= null
) {
229 getActivity().unregisterReceiver(mUploadFinishReceiver
);
230 mUploadFinishReceiver
= null
;
236 public void onStop() {
238 leaveTransferProgress();
243 public View
getView() {
244 return super.getView() == null ? mView
: super.getView();
252 public void onCreateOptionsMenu(Menu menu
, MenuInflater inflater
) {
253 super.onCreateOptionsMenu(menu
, inflater
);
254 inflater
.inflate(R
.menu
.file_actions_menu
, menu
);
255 MenuItem item
= menu
.findItem(R
.id
.action_see_details
);
257 item
.setVisible(false
);
258 item
.setEnabled(false
);
267 public void onPrepareOptionsMenu (Menu menu
) {
268 super.onPrepareOptionsMenu(menu
);
270 List
<Integer
> toHide
= new ArrayList
<Integer
>();
271 List
<Integer
> toShow
= new ArrayList
<Integer
>();
273 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
274 boolean downloading
= downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
);
275 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
276 boolean uploading
= uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
);
278 if (downloading
|| uploading
) {
279 toHide
.add(R
.id
.action_download_file
);
280 toHide
.add(R
.id
.action_rename_file
);
281 toHide
.add(R
.id
.action_remove_file
);
282 toHide
.add(R
.id
.action_open_file_with
);
284 toHide
.add(R
.id
.action_cancel_download
);
285 toShow
.add(R
.id
.action_cancel_upload
);
287 toHide
.add(R
.id
.action_cancel_upload
);
288 toShow
.add(R
.id
.action_cancel_download
);
291 } else if (mFile
!= null
&& mFile
.isDown()) {
292 toHide
.add(R
.id
.action_download_file
);
293 toHide
.add(R
.id
.action_cancel_download
);
294 toHide
.add(R
.id
.action_cancel_upload
);
296 toShow
.add(R
.id
.action_rename_file
);
297 toShow
.add(R
.id
.action_remove_file
);
298 toShow
.add(R
.id
.action_open_file_with
);
299 toShow
.add(R
.id
.action_sync_file
);
301 } else if (mFile
!= null
) {
302 toHide
.add(R
.id
.action_open_file_with
);
303 toHide
.add(R
.id
.action_cancel_download
);
304 toHide
.add(R
.id
.action_cancel_upload
);
305 toHide
.add(R
.id
.action_sync_file
);
307 toShow
.add(R
.id
.action_rename_file
);
308 toShow
.add(R
.id
.action_remove_file
);
309 toShow
.add(R
.id
.action_download_file
);
312 toHide
.add(R
.id
.action_open_file_with
);
313 toHide
.add(R
.id
.action_cancel_download
);
314 toHide
.add(R
.id
.action_cancel_upload
);
315 toHide
.add(R
.id
.action_sync_file
);
316 toHide
.add(R
.id
.action_download_file
);
317 toHide
.add(R
.id
.action_rename_file
);
318 toHide
.add(R
.id
.action_remove_file
);
322 MenuItem item
= null
;
323 for (int i
: toHide
) {
324 item
= menu
.findItem(i
);
326 item
.setVisible(false
);
327 item
.setEnabled(false
);
330 for (int i
: toShow
) {
331 item
= menu
.findItem(i
);
333 item
.setVisible(true
);
334 item
.setEnabled(true
);
344 public boolean onOptionsItemSelected(MenuItem item
) {
345 switch (item
.getItemId()) {
346 case R
.id
.action_open_file_with
: {
350 case R
.id
.action_remove_file
: {
354 case R
.id
.action_rename_file
: {
358 case R
.id
.action_download_file
:
359 case R
.id
.action_cancel_download
:
360 case R
.id
.action_cancel_upload
:
361 case R
.id
.action_sync_file
: {
371 public void onClick(View v
) {
373 case R
.id
.fdKeepInSync
: {
377 case R
.id
.fdCancelBtn
: {
382 Log_OC
.e(TAG
, "Incorrect view clicked!");
387 private void toggleKeepInSync() {
388 CheckBox cb
= (CheckBox
) getView().findViewById(R
.id
.fdKeepInSync
);
389 mFile
.setKeepInSync(cb
.isChecked());
390 mStorageManager
.saveFile(mFile
);
392 /// register the OCFile instance in the observer service to monitor local updates;
393 /// if necessary, the file is download
394 Intent intent
= new Intent(getActivity().getApplicationContext(),
395 FileObserverService
.class);
396 intent
.putExtra(FileObserverService
.KEY_FILE_CMD
,
398 FileObserverService
.CMD_ADD_OBSERVED_FILE
:
399 FileObserverService
.CMD_DEL_OBSERVED_FILE
));
400 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_FILE
, mFile
);
401 intent
.putExtra(FileObserverService
.KEY_CMD_ARG_ACCOUNT
, mAccount
);
402 getActivity().startService(intent
);
404 if (mFile
.keepInSync()) {
405 synchronizeFile(); // force an immediate synchronization
410 private void removeFile() {
411 ConfirmationDialogFragment confDialog
= ConfirmationDialogFragment
.newInstance(
412 R
.string
.confirmation_remove_alert
,
413 new String
[]{mFile
.getFileName()},
414 mFile
.isDown() ? R
.string
.confirmation_remove_remote_and_local
: R
.string
.confirmation_remove_remote
,
415 mFile
.isDown() ? R
.string
.confirmation_remove_local
: -1,
416 R
.string
.common_cancel
);
417 confDialog
.setOnConfirmationListener(this);
418 confDialog
.show(getFragmentManager(), FTAG_CONFIRMATION
);
422 private void renameFile() {
423 String fileName
= mFile
.getFileName();
424 int extensionStart
= mFile
.isDirectory() ?
-1 : fileName
.lastIndexOf(".");
425 int selectionEnd
= (extensionStart
>= 0) ? extensionStart
: fileName
.length();
426 EditNameDialog dialog
= EditNameDialog
.newInstance(getString(R
.string
.rename_dialog_title
), fileName
, 0, selectionEnd
, this);
427 dialog
.show(getFragmentManager(), "nameeditdialog");
430 private void synchronizeFile() {
431 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
432 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
433 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
434 downloaderBinder
.cancel(mAccount
, mFile
);
435 if (mFile
.isDown()) {
438 setButtonsForRemote();
441 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
442 uploaderBinder
.cancel(mAccount
, mFile
);
443 if (!mFile
.fileExists()) {
444 // TODO make something better
445 if (getActivity() instanceof FileDisplayActivity
) {
447 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
448 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
), FTAG
); // empty FileDetailFragment
449 transaction
.commit();
450 mContainerActivity
.onFileStateChanged();
452 getActivity().finish();
455 } else if (mFile
.isDown()) {
458 setButtonsForRemote();
462 mLastRemoteOperation
= new SynchronizeFileOperation(mFile
, null
, mStorageManager
, mAccount
, true
, false
, getActivity());
463 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
466 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
467 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
475 private void openFile() {
477 String storagePath
= mFile
.getStoragePath();
478 String encodedStoragePath
= WebdavUtils
.encodePath(storagePath
);
480 Intent i
= new Intent(Intent
.ACTION_VIEW
);
481 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mFile
.getMimetype());
482 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
485 } catch (Throwable t
) {
486 Log_OC
.e(TAG
, "Fail when trying to open with the mimeType provided from the ownCloud server: " + mFile
.getMimetype());
487 boolean toastIt
= true
;
488 String mimeType
= "";
490 Intent i
= new Intent(Intent
.ACTION_VIEW
);
491 mimeType
= MimeTypeMap
.getSingleton().getMimeTypeFromExtension(storagePath
.substring(storagePath
.lastIndexOf('.') + 1));
492 if (mimeType
== null
|| !mimeType
.equals(mFile
.getMimetype())) {
493 if (mimeType
!= null
) {
494 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), mimeType
);
497 i
.setDataAndType(Uri
.parse("file://"+ encodedStoragePath
), "*/*");
499 i
.setFlags(Intent
.FLAG_GRANT_READ_URI_PERMISSION
| Intent
.FLAG_GRANT_WRITE_URI_PERMISSION
);
504 } catch (IndexOutOfBoundsException e
) {
505 Log_OC
.e(TAG
, "Trying to find out MIME type of a file without extension: " + storagePath
);
507 } catch (ActivityNotFoundException e
) {
508 Log_OC
.e(TAG
, "No activity found to handle: " + storagePath
+ " with MIME type " + mimeType
+ " obtained from extension");
510 } catch (Throwable th
) {
511 Log_OC
.e(TAG
, "Unexpected problem when opening: " + storagePath
, th
);
515 Toast
.makeText(getActivity(), "There is no application to handle file " + mFile
.getFileName(), Toast
.LENGTH_SHORT
).show();
523 public void onConfirmation(String callerTag
) {
524 if (callerTag
.equals(FTAG_CONFIRMATION
)) {
525 if (mStorageManager
.getFileById(mFile
.getFileId()) != null
) {
526 mLastRemoteOperation
= new RemoveFileOperation( mFile
,
529 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
531 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
532 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
538 public void onNeutral(String callerTag
) {
540 if (mFile
.isDown() && (f
= new File(mFile
.getStoragePath())).exists()) {
542 mFile
.setStoragePath(null
);
543 mStorageManager
.saveFile(mFile
);
544 updateFileDetails(mFile
, mAccount
);
549 public void onCancel(String callerTag
) {
550 Log_OC
.d(TAG
, "REMOVAL CANCELED");
555 * Check if the fragment was created with an empty layout. An empty fragment can't show file details, must be replaced.
557 * @return True when the fragment was created with the empty layout.
559 public boolean isEmpty() {
560 return (mLayout
== R
.layout
.file_details_empty
|| mFile
== null
|| mAccount
== null
);
567 public OCFile
getFile(){
572 * Use this method to signal this Activity that it shall update its view.
574 * @param file : An {@link OCFile}
576 public void updateFileDetails(OCFile file
, Account ocAccount
) {
578 if (ocAccount
!= null
&& (
579 mStorageManager
== null
||
580 (mAccount
!= null
&& !mAccount
.equals(ocAccount
))
582 mStorageManager
= new FileDataStorageManager(ocAccount
, getActivity().getApplicationContext().getContentResolver());
584 mAccount
= ocAccount
;
585 updateFileDetails(false
, false
);
589 * Updates the view with all relevant details about that file.
591 * TODO Remove parameter when the transferring state of files is kept in database.
593 * TODO REFACTORING! this method called 5 times before every time the fragment is shown!
595 * @param transferring Flag signaling if the file should be considered as downloading or uploading,
596 * although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and
597 * {@link FileUploaderBinder#isUploading(Account, OCFile)} return false.
599 * @param refresh If 'true', try to refresh the hold file from the database
601 public void updateFileDetails(boolean transferring
, boolean refresh
) {
605 if (refresh
&& mStorageManager
!= null
) {
606 mFile
= mStorageManager
.getFileByPath(mFile
.getRemotePath());
610 setFilename(mFile
.getFileName());
611 setFiletype(mFile
.getMimetype());
612 setFilesize(mFile
.getFileLength());
613 if(ocVersionSupportsTimeCreated()){
614 setTimeCreated(mFile
.getCreationTimestamp());
617 setTimeModified(mFile
.getModificationTimestamp());
619 CheckBox cb
= (CheckBox
)getView().findViewById(R
.id
.fdKeepInSync
);
620 cb
.setChecked(mFile
.keepInSync());
622 // configure UI for depending upon local state of the file
623 //if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
624 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
625 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
626 if (transferring
|| (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) || (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
))) {
627 setButtonsForTransferring();
629 } else if (mFile
.isDown()) {
634 // TODO load default preview image; when the local file is removed, the preview remains there
635 setButtonsForRemote();
638 getView().invalidate();
642 * Checks if the fragment is ready to show details of a OCFile
644 * @return 'True' when the fragment is ready to show details of a file
646 private boolean readyToShow() {
647 return (mFile
!= null
&& mAccount
!= null
&& mLayout
== R
.layout
.file_details_fragment
);
652 * Updates the filename in view
653 * @param filename to set
655 private void setFilename(String filename
) {
656 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdFilename
);
658 tv
.setText(filename
);
662 * Updates the MIME type in view
663 * @param mimetype to set
665 private void setFiletype(String mimetype
) {
666 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdType
);
668 String printableMimetype
= DisplayUtils
.convertMIMEtoPrettyPrint(mimetype
);;
669 tv
.setText(printableMimetype
);
671 ImageView iv
= (ImageView
) getView().findViewById(R
.id
.fdIcon
);
673 iv
.setImageResource(DisplayUtils
.getResourceId(mimetype
));
678 * Updates the file size in view
679 * @param filesize in bytes to set
681 private void setFilesize(long filesize
) {
682 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdSize
);
684 tv
.setText(DisplayUtils
.bytesToHumanReadable(filesize
));
688 * Updates the time that the file was created in view
689 * @param milliseconds Unix time to set
691 private void setTimeCreated(long milliseconds
){
692 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdCreated
);
693 TextView tvLabel
= (TextView
) getView().findViewById(R
.id
.fdCreatedLabel
);
695 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
696 tv
.setVisibility(View
.VISIBLE
);
697 tvLabel
.setVisibility(View
.VISIBLE
);
702 * Updates the time that the file was last modified
703 * @param milliseconds Unix time to set
705 private void setTimeModified(long milliseconds
){
706 TextView tv
= (TextView
) getView().findViewById(R
.id
.fdModified
);
708 tv
.setText(DisplayUtils
.unixTimeToHumanReadable(milliseconds
));
713 * Enables or disables buttons for a file being downloaded
715 private void setButtonsForTransferring() {
717 // let's protect the user from himself ;)
718 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(false
);
720 // show the progress bar for the transfer
721 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.VISIBLE
);
722 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
723 progressText
.setVisibility(View
.VISIBLE
);
724 FileDownloaderBinder downloaderBinder
= mContainerActivity
.getFileDownloaderBinder();
725 FileUploaderBinder uploaderBinder
= mContainerActivity
.getFileUploaderBinder();
726 if (downloaderBinder
!= null
&& downloaderBinder
.isDownloading(mAccount
, mFile
)) {
727 progressText
.setText(R
.string
.downloader_download_in_progress_ticker
);
728 } else if (uploaderBinder
!= null
&& uploaderBinder
.isUploading(mAccount
, mFile
)) {
729 progressText
.setText(R
.string
.uploader_upload_in_progress_ticker
);
735 * Enables or disables buttons for a file locally available
737 private void setButtonsForDown() {
739 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
741 // hides the progress bar
742 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
743 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
744 progressText
.setVisibility(View
.GONE
);
749 * Enables or disables buttons for a file not locally available
751 private void setButtonsForRemote() {
753 getView().findViewById(R
.id
.fdKeepInSync
).setEnabled(true
);
755 // hides the progress bar
756 getView().findViewById(R
.id
.fdProgressBlock
).setVisibility(View
.GONE
);
757 TextView progressText
= (TextView
)getView().findViewById(R
.id
.fdProgressText
);
758 progressText
.setVisibility(View
.GONE
);
764 * In ownCloud 3.X.X and 4.X.X there is a bug that SabreDAV does not return
765 * the time that the file was created. There is a chance that this will
766 * be fixed in future versions. Use this method to check if this version of
767 * ownCloud has this fix.
768 * @return True, if ownCloud the ownCloud version is supporting creation time
770 private boolean ocVersionSupportsTimeCreated(){
771 /*if(mAccount != null){
772 AccountManager accManager = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);
773 OwnCloudVersion ocVersion = new OwnCloudVersion(accManager
774 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
775 if(ocVersion.compareTo(new OwnCloudVersion(0x030000)) < 0) {
784 * Once the file upload has finished -> update view
786 * Being notified about the finish of an upload is necessary for the next sequence:
787 * 1. Upload a big file.
788 * 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
789 * of its containing folder; the the server includes it in the PROPFIND requests although it's not fully upload.
790 * 3. Click the file in the list to see its details.
791 * 4. Wait for the upload finishes; at this moment, the details view must be refreshed to enable the action buttons.
793 private class UploadFinishReceiver
extends BroadcastReceiver
{
795 public void onReceive(Context context
, Intent intent
) {
796 String accountName
= intent
.getStringExtra(FileUploader
.ACCOUNT_NAME
);
798 if (!isEmpty() && accountName
.equals(mAccount
.name
)) {
799 boolean uploadWasFine
= intent
.getBooleanExtra(FileUploader
.EXTRA_UPLOAD_RESULT
, false
);
800 String uploadRemotePath
= intent
.getStringExtra(FileUploader
.EXTRA_REMOTE_PATH
);
801 boolean renamedInUpload
= mFile
.getRemotePath().equals(intent
.getStringExtra(FileUploader
.EXTRA_OLD_REMOTE_PATH
));
802 if (mFile
.getRemotePath().equals(uploadRemotePath
) ||
805 mFile
= mStorageManager
.getFileByPath(uploadRemotePath
);
807 if (renamedInUpload
) {
808 String newName
= (new File(uploadRemotePath
)).getName();
809 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), String
.format(getString(R
.string
.filedetails_renamed_in_upload_msg
), newName
), Toast
.LENGTH_LONG
);
812 getSherlockActivity().removeStickyBroadcast(intent
); // not the best place to do this; a small refactorization of BroadcastReceivers should be done
813 updateFileDetails(false
, false
); // it updates the buttons; must be called although !uploadWasFine; interrupted uploads still leave an incomplete file in the server
820 public void onDismiss(EditNameDialog dialog
) {
821 if (dialog
.getResult()) {
822 String newFilename
= dialog
.getNewFilename();
823 Log_OC
.d(TAG
, "name edit dialog dismissed with new name " + newFilename
);
824 mLastRemoteOperation
= new RenameFileOperation( mFile
,
827 new FileDataStorageManager(mAccount
, getActivity().getContentResolver()));
828 mLastRemoteOperation
.execute(mAccount
, getSherlockActivity(), this, mHandler
, getSherlockActivity());
829 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
830 getActivity().showDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
839 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
840 if (operation
.equals(mLastRemoteOperation
)) {
841 if (operation
instanceof RemoveFileOperation
) {
842 onRemoveFileOperationFinish((RemoveFileOperation
)operation
, result
);
844 } else if (operation
instanceof RenameFileOperation
) {
845 onRenameFileOperationFinish((RenameFileOperation
)operation
, result
);
847 } else if (operation
instanceof SynchronizeFileOperation
) {
848 onSynchronizeFileOperationFinish((SynchronizeFileOperation
)operation
, result
);
854 private void onRemoveFileOperationFinish(RemoveFileOperation operation
, RemoteOperationResult result
) {
855 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
856 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
858 if (result
.isSuccess()) {
859 Toast msg
= Toast
.makeText(getActivity().getApplicationContext(), R
.string
.remove_success_msg
, Toast
.LENGTH_LONG
);
861 if (inDisplayActivity
) {
863 FragmentTransaction transaction
= getActivity().getSupportFragmentManager().beginTransaction();
864 transaction
.replace(R
.id
.file_details_container
, new FileDetailFragment(null
, null
)); // empty FileDetailFragment
865 transaction
.commit();
866 mContainerActivity
.onFileStateChanged();
868 getActivity().finish();
872 Toast msg
= Toast
.makeText(getActivity(), R
.string
.remove_fail_msg
, Toast
.LENGTH_LONG
);
874 if (result
.isSslRecoverableException()) {
875 // TODO show the SSL warning dialog
880 private void onRenameFileOperationFinish(RenameFileOperation operation
, RemoteOperationResult result
) {
881 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
882 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
884 if (result
.isSuccess()) {
885 updateFileDetails(((RenameFileOperation
)operation
).getFile(), mAccount
);
886 mContainerActivity
.onFileStateChanged();
889 if (result
.getCode().equals(ResultCode
.INVALID_LOCAL_FILE_NAME
)) {
890 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_local_fail_msg
, Toast
.LENGTH_LONG
);
892 // TODO throw again the new rename dialog
894 Toast msg
= Toast
.makeText(getActivity(), R
.string
.rename_server_fail_msg
, Toast
.LENGTH_LONG
);
896 if (result
.isSslRecoverableException()) {
897 // TODO show the SSL warning dialog
903 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation
, RemoteOperationResult result
) {
904 boolean inDisplayActivity
= getActivity() instanceof FileDisplayActivity
;
905 getActivity().dismissDialog((inDisplayActivity
)? FileDisplayActivity
.DIALOG_SHORT_WAIT
: FileDetailActivity
.DIALOG_SHORT_WAIT
);
907 if (!result
.isSuccess()) {
908 if (result
.getCode() == ResultCode
.SYNC_CONFLICT
) {
909 Intent i
= new Intent(getActivity(), ConflictsResolveActivity
.class);
910 i
.putExtra(ConflictsResolveActivity
.EXTRA_FILE
, mFile
);
911 i
.putExtra(ConflictsResolveActivity
.EXTRA_ACCOUNT
, mAccount
);
915 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_fail_msg
, Toast
.LENGTH_LONG
);
919 if (mFile
.isDown()) {
923 setButtonsForRemote();
927 if (operation
.transferWasRequested()) {
928 setButtonsForTransferring();
929 mContainerActivity
.onFileStateChanged(); // this is not working; FileDownloader won't do NOTHING at all until this method finishes, so
930 // checking the service to see if the file is downloading results in FALSE
932 Toast msg
= Toast
.makeText(getActivity(), R
.string
.sync_file_nothing_to_do_msg
, Toast
.LENGTH_LONG
);
934 if (mFile
.isDown()) {
938 setButtonsForRemote();
945 public void listenForTransferProgress() {
946 if (mProgressListener
!= null
) {
947 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
948 mContainerActivity
.getFileDownloaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
950 if (mContainerActivity
.getFileUploaderBinder() != null
) {
951 mContainerActivity
.getFileUploaderBinder().addDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
957 public void leaveTransferProgress() {
958 if (mProgressListener
!= null
) {
959 if (mContainerActivity
.getFileDownloaderBinder() != null
) {
960 mContainerActivity
.getFileDownloaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
962 if (mContainerActivity
.getFileUploaderBinder() != null
) {
963 mContainerActivity
.getFileUploaderBinder().removeDatatransferProgressListener(mProgressListener
, mAccount
, mFile
);
971 * Helper class responsible for updating the progress bar shown for file uploading or downloading
973 * @author David A. Velasco
975 private class ProgressListener
implements OnDatatransferProgressListener
{
976 int mLastPercent
= 0;
977 WeakReference
<ProgressBar
> mProgressBar
= null
;
979 ProgressListener(ProgressBar progressBar
) {
980 mProgressBar
= new WeakReference
<ProgressBar
>(progressBar
);
984 public void onTransferProgress(long progressRate
) {
985 // old method, nothing here
989 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filename
) {
990 int percent
= (int)(100.0*((double)totalTransferredSoFar
)/((double)totalToTransfer
));
991 if (percent
!= mLastPercent
) {
992 ProgressBar pb
= mProgressBar
.get();
994 pb
.setProgress(percent
);
998 mLastPercent
= percent
;
1004 // this is a temporary class for sharing purposes, it need to be replaced in transfer service
1005 @SuppressWarnings("unused")
1006 private class ShareRunnable implements Runnable {
1007 private String mPath;
1009 public ShareRunnable(String path) {
1014 AccountManager am = AccountManager.get(getActivity());
1015 Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
1016 OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
1017 String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv);
1019 Log_OC.d("share", "sharing for version " + ocv.toString());
1021 if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
1022 String APPS_PATH = "/apps/files_sharing/";
1023 String SHARE_PATH = "ajax/share.php";
1025 String SHARED_PATH = "/apps/files_sharing/get.php?token=";
1027 final String WEBDAV_SCRIPT = "webdav.php";
1028 final String WEBDAV_FILES_LOCATION = "/files/";
1030 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(account, getActivity().getApplicationContext());
1031 HttpConnectionManagerParams params = new HttpConnectionManagerParams();
1032 params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);
1034 //wc.getParams().setParameter("http.protocol.single-cookie-header", true);
1035 //wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
1037 PostMethod post = new PostMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH);
1039 post.addRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8" );
1040 post.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1041 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
1042 Log_OC.d("share", mPath+"");
1043 formparams.add(new BasicNameValuePair("sources",mPath));
1044 formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
1045 formparams.add(new BasicNameValuePair("permissions", "0"));
1046 post.setRequestEntity(new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));
1050 PropFindMethod find = new PropFindMethod(url+"/");
1051 find.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1052 Log_OC.d("sharer", ""+ url+"/");
1054 for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
1055 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1058 int status2 = wc.executeMethod(find);
1060 Log_OC.d("sharer", "propstatus "+status2);
1062 GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
1063 get.addRequestHeader("Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
1065 status2 = wc.executeMethod(get);
1067 Log_OC.d("sharer", "getstatus "+status2);
1068 Log_OC.d("sharer", "" + get.getResponseBodyAsString());
1070 for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
1071 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1074 status = wc.executeMethod(post);
1075 for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
1076 Log_OC.d("sharer-h", a.getName() + ":"+a.getValue());
1078 for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
1079 Log_OC.d("sharer", a.getName() + ":"+a.getValue());
1081 String resp = post.getResponseBodyAsString();
1082 Log_OC.d("share", ""+post.getURI().toString());
1083 Log_OC.d("share", "returned status " + status);
1084 Log_OC.d("share", " " +resp);
1086 if(status != HttpStatus.SC_OK ||resp == null || resp.equals("") || resp.startsWith("false")) {
1090 JSONObject jsonObject = new JSONObject (resp);
1091 String jsonStatus = jsonObject.getString("status");
1092 if(!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success");
1094 String token = jsonObject.getString("data");
1095 String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
1096 Log_OC.d("Actions:shareFile ok", "url: " + uri);
1098 } catch (Exception e) {
1099 e.printStackTrace();
1102 } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {