diff options
Diffstat (limited to 'android/source/src/java/org/libreoffice/storage')
17 files changed, 0 insertions, 1922 deletions
diff --git a/android/source/src/java/org/libreoffice/storage/DocumentProviderFactory.java b/android/source/src/java/org/libreoffice/storage/DocumentProviderFactory.java deleted file mode 100644 index acf5aebcd6c6..000000000000 --- a/android/source/src/java/org/libreoffice/storage/DocumentProviderFactory.java +++ /dev/null @@ -1,128 +0,0 @@ -/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.libreoffice.storage; - -import java.util.HashSet; -import java.util.Set; - -import org.libreoffice.storage.external.ExtsdDocumentsProvider; -import org.libreoffice.storage.external.OTGDocumentsProvider; -import org.libreoffice.storage.local.LocalDocumentsDirectoryProvider; -import org.libreoffice.storage.local.LocalDocumentsProvider; -import org.libreoffice.storage.owncloud.OwnCloudProvider; - -import android.content.Context; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; - -/** - * Keeps the instances of the available IDocumentProviders in the system. - * Instances are maintained in a sorted list and providers have to be - * accessed from their position. - * - * The factory follows the Singleton pattern, there is only one instance of it - * in the application and it must be retrieved with - * DocumentProviderFactory.getInstance(). - */ -public final class DocumentProviderFactory { - public static int EXTSD_PROVIDER_INDEX = 2; - public static int OTG_PROVIDER_INDEX = 3; - - /** - * Private factory instance for the Singleton pattern. - */ - private static DocumentProviderFactory instance = null; - - private IDocumentProvider[] providers; - - private String[] providerNames; - - private DocumentProviderFactory() { - // private to prevent external instances of the factory - } - - /** - * Initializes the factory with some context. If this method is called for - * twice or more times those calls will have no effect. - * - * @param context - * Application context for the factory. - */ - public static void initialize(Context context) { - if (instance == null) { - // initialize instance - instance = new DocumentProviderFactory(); - - // initialize document providers list - instance.providers = new IDocumentProvider[5]; - instance.providers[0] = new LocalDocumentsDirectoryProvider(0); - instance.providers[1] = new LocalDocumentsProvider(1); - instance.providers[OTG_PROVIDER_INDEX] = new OTGDocumentsProvider(OTG_PROVIDER_INDEX, context); - instance.providers[4] = new OwnCloudProvider(4, context); - - instance.providers[EXTSD_PROVIDER_INDEX] = new ExtsdDocumentsProvider(EXTSD_PROVIDER_INDEX, context); - - // initialize document provider names list - instance.providerNames = new String[instance.providers.length]; - for (int i = 0; i < instance.providers.length; i++) { - instance.providerNames[i] = context.getString(instance - .getProvider(i).getNameResource()); - } - } - } - - /** - * Retrieve the unique instance of the factory. - * - * @return the unique factory object or null if it is not yet initialized. - */ - public static DocumentProviderFactory getInstance() { - return instance; - } - - /** - * Retrieve the provider associated to a certain id. - * - * @param id - * @return document provider with that id. - */ - public IDocumentProvider getProvider(int id) { - // as for now, id == position in providers array - return providers[id]; - } - - /** - * Returns a sorted list of the names of the providers. Order is meaningful - * to retrieve the actual provider object with getProvider(). - * - * @return Array with the names of the available providers. - */ - public String[] getNames() { - return providerNames; - } - - /** - * Returns the default provider. - * - * @return default provider. - */ - public IDocumentProvider getDefaultProvider() { - return providers[0]; - } - - public Set<OnSharedPreferenceChangeListener> getChangeListeners() { - Set<OnSharedPreferenceChangeListener> listeners = - new HashSet<OnSharedPreferenceChangeListener>(); - for (IDocumentProvider provider : providers) { - if (provider instanceof OnSharedPreferenceChangeListener) - listeners.add((OnSharedPreferenceChangeListener) provider); - } - return listeners; - } -} diff --git a/android/source/src/java/org/libreoffice/storage/DocumentProviderSettingsActivity.java b/android/source/src/java/org/libreoffice/storage/DocumentProviderSettingsActivity.java deleted file mode 100644 index b842e79fafd6..000000000000 --- a/android/source/src/java/org/libreoffice/storage/DocumentProviderSettingsActivity.java +++ /dev/null @@ -1,102 +0,0 @@ -/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.libreoffice.storage; - -import java.util.Set; - -import org.libreoffice.R; -import org.libreoffice.storage.external.BrowserSelectorActivity; - -import android.content.Intent; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; -import android.os.Bundle; -import android.preference.Preference; -import android.preference.PreferenceFragment; -import android.preference.PreferenceManager; -import android.preference.PreferenceScreen; -import android.support.v7.app.AppCompatActivity; - -public class DocumentProviderSettingsActivity extends AppCompatActivity { - - public static final String KEY_PREF_OWNCLOUD_SERVER = "pref_server_url"; - public static final String KEY_PREF_OWNCLOUD_USER_NAME = "pref_user_name"; - public static final String KEY_PREF_OWNCLOUD_PASSWORD = "pref_password"; - public static final String KEY_PREF_EXTERNAL_SD_PATH_URI = "pref_extsd_path_uri"; - public static final String KEY_PREF_OTG_PATH_URI = "pref_otg_path_uri"; - - private Set<OnSharedPreferenceChangeListener> listeners; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // Display the fragment as the main content. - getFragmentManager().beginTransaction() - .replace(android.R.id.content, new SettingsFragment()).commit(); - } - - @Override - protected void onResume() { - super.onResume(); - listeners = DocumentProviderFactory.getInstance().getChangeListeners(); - for (OnSharedPreferenceChangeListener listener : listeners) { - PreferenceManager.getDefaultSharedPreferences(this) - .registerOnSharedPreferenceChangeListener(listener); - } - } - - @Override - protected void onPause() { - super.onPause(); - for (OnSharedPreferenceChangeListener listener : listeners) { - PreferenceManager.getDefaultSharedPreferences(this) - .unregisterOnSharedPreferenceChangeListener(listener); - } - } - - public static class SettingsFragment extends PreferenceFragment { - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // Load the preferences from an XML resource - addPreferencesFromResource(R.xml.documentprovider_preferences); - - PreferenceScreen extSDPreference = - (PreferenceScreen)findPreference(KEY_PREF_EXTERNAL_SD_PATH_URI); - PreferenceScreen otgPreference = - (PreferenceScreen)findPreference(KEY_PREF_OTG_PATH_URI); - - extSDPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - startBrowserSelectorActivity(KEY_PREF_EXTERNAL_SD_PATH_URI, - BrowserSelectorActivity.MODE_EXT_SD); - return true; - } - }); - otgPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - startBrowserSelectorActivity(KEY_PREF_OTG_PATH_URI, - BrowserSelectorActivity.MODE_OTG); - return true; - } - }); - - } - - private void startBrowserSelectorActivity(String prefKey, String mode) { - Intent i = new Intent(getActivity(), BrowserSelectorActivity.class); - i.putExtra(BrowserSelectorActivity.PREFERENCE_KEY_EXTRA, prefKey); - i.putExtra(BrowserSelectorActivity.MODE_EXTRA, mode); - startActivity(i); - } - - } -} diff --git a/android/source/src/java/org/libreoffice/storage/IDocumentProvider.java b/android/source/src/java/org/libreoffice/storage/IDocumentProvider.java deleted file mode 100644 index 044d7ddb422b..000000000000 --- a/android/source/src/java/org/libreoffice/storage/IDocumentProvider.java +++ /dev/null @@ -1,70 +0,0 @@ -/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.libreoffice.storage; - -import android.content.Context; - -import java.net.URI; - -/** - * Represents a Document Provider, an object able to provide documents from a - * certain source (e.g. local documents, DropBox, Google Docs). - */ -public interface IDocumentProvider { - - /** - * Provides the content root element for the Document Provider. - * - * @return Content root element. - * @throws RuntimeException in case of error. - * @param context - */ - IFile getRootDirectory(Context context); - - /** - * Transforms some URI into the IFile object that represents that content. - * - * - * @param context - * @param uri - * URI pointing to some content object that has been previously - * retrieved with IFile.getUri(). - * @return IFile object pointing to the content represented by uri. - * @throws RuntimeException in case of error. - */ - IFile createFromUri(Context context, URI uri); - - /** - * Get internationalized name for this provider. This name is intended to be - * shown in the UI. - * - * @return string resource pointing to the provider name. - */ - int getNameResource(); - - /** - * Provides the unique ID for a document provider instance in a program. - * - * This ID should be set when the instance is built. It could be used to - * tell two instances of the same document provider apart, e. g. two - * instances of OwnCloudProvider pointing to different servers. - * - * @return Unique ID for a document provider instance. - */ - int getId(); - - /** - * Checks if the Document Provider is available or not. - * - * @return A boolean value based on provider availability. - * @param context - */ - boolean checkProviderAvailability(Context context); -} diff --git a/android/source/src/java/org/libreoffice/storage/IFile.java b/android/source/src/java/org/libreoffice/storage/IFile.java deleted file mode 100644 index c9cfa7f1198d..000000000000 --- a/android/source/src/java/org/libreoffice/storage/IFile.java +++ /dev/null @@ -1,116 +0,0 @@ -/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.libreoffice.storage; - -import android.content.Context; - -import java.io.File; -import java.io.FileFilter; -import java.net.URI; -import java.util.Date; -import java.util.List; - -/** - * An abstraction of the File class, intended to be implemented by different - * Document Providers. - * - * It represents a file or a directory in the context of a certain Document - * Provider. It wraps the file-related operations and provides access to the - * final document as a local File, downloading it if necessary. - */ -public interface IFile { - - /** - * Provides a URI that represents this IFile object. - * - * @return URI that represents this IFile object in the context of the - * Document Provider that created it. The URI can be transformed - * back into an IFile object with IDocumentProvider.createFromUri(). - */ - URI getUri(); - - /** - * Returns the name of the file or directory represented by this file. - * - * @return This file's name. - */ - String getName(); - - /** - * Indicates if this file represents a directory in the context of the - * Document Provider which originated it. - * - * @return true if this file is a directory, false otherwise. - */ - boolean isDirectory(); - - /** - * Returns the file size in bytes. - * - * @return file size in bytes, 0 if the file does not exist. - */ - long getSize(); - - /** - * Returns the time when this file was last modified, measured in - * milliseconds since January 1st, 1970, midnight. - * - * @return time when this file was last modified, or 0 if the file does not - * exist. - */ - Date getLastModified(); - - /** - * Returns a list containing the files in the directory represented by this - * file. - * - * @return list of files contained by this directory, or an empty list if - * this is not a directory. - * @throws RuntimeException in case of error. - */ - List<IFile> listFiles(); - - /** - * Gets the list of files contained in the directory represented by this - * file, and filters it through some FilenameFilter. - * - * @param filter - * the filter to match names against. - * @return filtered list of files contained by this directory, or an empty - * list if this is not a directory. - * @throws RuntimeException in case of error. - */ - List<IFile> listFiles(FileFilter filter); - - /** - * Returns the pparent of this file. - * - * @return this file's parent or null if it does not have it. - * @param context - */ - IFile getParent(Context context); - - /** - * Returns the document wrapped by this IFile as a local file. The result - * for a directory is not defined. - * - * @return local file containing the document wrapped by this object. - * @throws RuntimeException in case of error. - */ - File getDocument(); - - /** - * Replaces the wrapped document with a new version of it. - * - * @param file - * A local file pointing to the new version of the document. - */ - void saveDocument(File file); -} diff --git a/android/source/src/java/org/libreoffice/storage/IOUtils.java b/android/source/src/java/org/libreoffice/storage/IOUtils.java deleted file mode 100644 index f345f5cbed3b..000000000000 --- a/android/source/src/java/org/libreoffice/storage/IOUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.libreoffice.storage; - -import android.util.Log; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * File IO related methods. - */ -public class IOUtils { - private static final int BUFFER_SIZE = 1024 * 8; - private static final String LOGTAG = IOUtils.class.getSimpleName(); - - public static File getFileFromURIString(String URIpath) throws IllegalArgumentException{ - try{ - return new File(new URI(URIpath)); - } catch (URISyntaxException e) { - //should not happen as all URIs are system generated - Log.wtf(LOGTAG, e.getReason()); - return null; - } - } - - public static boolean isInvalidFile(File f) { - return f == null || !f.exists() || f.getTotalSpace() == 0 - || !f.canRead() || !f.canWrite(); - } - - public static int copy(InputStream input, OutputStream output) throws Exception { - byte[] buffer = new byte[BUFFER_SIZE]; - - BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE); - BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE); - - int count = 0, n = 0; - try { - while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) { - out.write(buffer, 0, n); - count += n; - } - out.flush(); - } finally { - if (out != null) out.close(); - if (in != null) in.close(); - } - - return count; - } - -} diff --git a/android/source/src/java/org/libreoffice/storage/external/BrowserSelectorActivity.java b/android/source/src/java/org/libreoffice/storage/external/BrowserSelectorActivity.java deleted file mode 100644 index 07b64623b701..000000000000 --- a/android/source/src/java/org/libreoffice/storage/external/BrowserSelectorActivity.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.libreoffice.storage.external; - -import android.annotation.TargetApi; -import android.content.ContentResolver; -import android.content.Intent; -import android.content.SharedPreferences; -import android.content.UriPermission; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.v7.app.AppCompatActivity; -import android.util.Log; - -import org.libreoffice.R; -import org.libreoffice.storage.DocumentProviderFactory; - -import java.util.Set; - -/** - * Activity to select which directory browser to use. - * Android 5+ will use the DocumentTree intent to locate a browser. - * Android 4+ & OTG will use the internal directory browser. - */ -public class BrowserSelectorActivity extends AppCompatActivity { - public static final String PREFERENCE_KEY_EXTRA = "org.libreoffice.pref_key_extra"; - public static final String MODE_EXTRA = "org.libreoffice.mode_extra"; - public static final String MODE_OTG = "OTG"; - public static final String MODE_EXT_SD = "EXT_SD"; - - private static final String LOGTAG = BrowserSelectorActivity.class.getSimpleName(); - private static final int REQUEST_DOCUMENT_TREE = 1; - private static final int REQUEST_INTERNAL_BROWSER = 2; - private Set<SharedPreferences.OnSharedPreferenceChangeListener> listeners; - private String preferenceKey; - private SharedPreferences preferences; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - preferenceKey = getIntent().getStringExtra(PREFERENCE_KEY_EXTRA); - preferences = PreferenceManager.getDefaultSharedPreferences(this); - String mode = getIntent().getStringExtra(MODE_EXTRA); - - if(mode.equals(MODE_EXT_SD)) { - findSDCard(); - } else if (mode.equals(MODE_OTG)) { - findOTGDevice(); - } - } - - private void findOTGDevice() { - useInternalBrowser(DocumentProviderFactory.OTG_PROVIDER_INDEX); - } - - private void findSDCard() { - if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - useDocumentTreeBrowser(); - } else { - useInternalBrowser(DocumentProviderFactory.EXTSD_PROVIDER_INDEX); - } - } - - private void useInternalBrowser(int providerIndex) { - IExternalDocumentProvider provider = - (IExternalDocumentProvider) DocumentProviderFactory.getInstance() - .getProvider(providerIndex); - String previousDirectoryPath = preferences.getString(preferenceKey, provider.guessRootURI(this)); - Intent i = new Intent(this, DirectoryBrowserActivity.class); - i.putExtra(DirectoryBrowserActivity.DIRECTORY_PATH_EXTRA, previousDirectoryPath); - startActivityForResult(i, REQUEST_INTERNAL_BROWSER); - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - private void useDocumentTreeBrowser() { - Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); - startActivityForResult(i, REQUEST_DOCUMENT_TREE); - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - //listeners are registered here as onActivityResult is called before onResume - super.onActivityResult(requestCode, resultCode, data); - - registerListeners(); - if(resultCode == RESULT_OK) { - switch(requestCode) { - case REQUEST_DOCUMENT_TREE: - Uri treeUri = data.getData(); - preferences.edit() - .putString(preferenceKey, treeUri.toString()) - .apply(); - - updatePersistedUriPermission(treeUri); - getContentResolver().takePersistableUriPermission(treeUri, - Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION); - break; - - case REQUEST_INTERNAL_BROWSER: - Uri fileUri = data.getData(); - preferences.edit() - .putString(preferenceKey, fileUri.toString()) - .apply(); - break; - default: - } - } - unregisterListeners(); - Log.d(LOGTAG, "Preference saved: " + - preferences.getString(preferenceKey, getString(R.string.directory_not_saved))); - finish(); - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - private void updatePersistedUriPermission(Uri treeUri) { - freePreviousUriPermissions(); - - //TODO: Use non-emulator Android 5+ device to check if needed - /*this.grantUriPermission(this.getPackageName(), - treeUri, - Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION); */ - - getContentResolver().takePersistableUriPermission(treeUri, - Intent.FLAG_GRANT_READ_URI_PERMISSION | - Intent.FLAG_GRANT_WRITE_URI_PERMISSION); - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP) - private void freePreviousUriPermissions() { - ContentResolver cr = getContentResolver(); - for (UriPermission uriPermission : cr.getPersistedUriPermissions()) { - cr.releasePersistableUriPermission(uriPermission.getUri(), 0); - } - } - - private void registerListeners() { - listeners = DocumentProviderFactory.getInstance().getChangeListeners(); - for (SharedPreferences.OnSharedPreferenceChangeListener listener : listeners) { - PreferenceManager.getDefaultSharedPreferences(this) - .registerOnSharedPreferenceChangeListener(listener); - } - } - - private void unregisterListeners() { - for (SharedPreferences.OnSharedPreferenceChangeListener listener : listeners) { - PreferenceManager.getDefaultSharedPreferences(this) - .unregisterOnSharedPreferenceChangeListener(listener); - } - } -} diff --git a/android/source/src/java/org/libreoffice/storage/external/DirectoryBrowserActivity.java b/android/source/src/java/org/libreoffice/storage/external/DirectoryBrowserActivity.java deleted file mode 100644 index 1cf9f52fa7c0..000000000000 --- a/android/source/src/java/org/libreoffice/storage/external/DirectoryBrowserActivity.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.libreoffice.storage.external; - - -import android.app.Fragment; -import android.app.FragmentManager; -import android.content.Intent; -import android.os.Bundle; -import android.support.annotation.Nullable; -import android.support.v7.app.AppCompatActivity; - -import org.libreoffice.R; - -/** - * Container for DirectoryBrowserFragment - */ -public class DirectoryBrowserActivity extends AppCompatActivity { - public static final String DIRECTORY_PATH_EXTRA = "org.libreoffice.directory_path_extra"; - - @Override - protected void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - Intent data = getIntent(); - String initialPath = data.getStringExtra(DIRECTORY_PATH_EXTRA); - - setContentView(R.layout.activity_directory_browser); - FragmentManager fm = getFragmentManager(); - Fragment fragment = DirectoryBrowserFragment.newInstance(initialPath); - fm.beginTransaction() - .add(R.id.fragment_container, fragment) - .commit(); - } - - @Override - public void onBackPressed() { - FragmentManager fm = getFragmentManager(); - if(fm.getBackStackEntryCount() > 0) { - fm.popBackStack(); - } else { - super.onBackPressed(); - } - } -} diff --git a/android/source/src/java/org/libreoffice/storage/external/DirectoryBrowserFragment.java b/android/source/src/java/org/libreoffice/storage/external/DirectoryBrowserFragment.java deleted file mode 100644 index 18165650a617..000000000000 --- a/android/source/src/java/org/libreoffice/storage/external/DirectoryBrowserFragment.java +++ /dev/null @@ -1,199 +0,0 @@ -package org.libreoffice.storage.external; - -import android.app.Activity; -import android.app.Fragment; -import android.content.Context; -import android.content.Intent; -import android.net.Uri; -import android.os.Bundle; -import android.os.Environment; -import android.support.annotation.Nullable; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.ImageView; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; - -import org.libreoffice.R; -import org.libreoffice.storage.IOUtils; - -import java.io.File; -import java.util.ArrayList; -import java.util.Comparator; - -/** - * A simple directory browser. - */ -public class DirectoryBrowserFragment extends Fragment { - private static final String LOGTAG = DirectoryBrowserFragment.class.getSimpleName(); - private static final String INITIAL_PATH_URI_KEY = "initial_path"; - private File currentDirectory; - private FileArrayAdapter directoryAdapter; - - public static DirectoryBrowserFragment newInstance(String initialPathURI) { - Bundle args = new Bundle(); - args.putString(INITIAL_PATH_URI_KEY, initialPathURI); - DirectoryBrowserFragment fragment = new DirectoryBrowserFragment(); - fragment.setArguments(args); - Log.d(LOGTAG, "Saved path: " + initialPathURI); - - return fragment; - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - String initialPathURI = getArguments().getString(INITIAL_PATH_URI_KEY); - setupCurrentDirectory(initialPathURI); - } - - @Nullable - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View v = inflater.inflate(R.layout.fragment_directory_browser, container, false); - - final EditText directoryHeader = v.findViewById(R.id.directory_header); - Button directorySearchButton = v.findViewById(R.id.directory_search_button); - Button positiveButton = v.findViewById(R.id.confirm_button); - Button negativeButton = v.findViewById(R.id.cancel_button); - ImageView upImage = v.findViewById(R.id.up_image); - ListView directoryListView = v.findViewById(R.id.directory_list); - - directoryHeader.setText(currentDirectory.getPath()); - directorySearchButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - String currentPath = currentDirectory.getAbsolutePath(); - String enteredPath = directoryHeader.getText().toString(); - File testDirectory = new File(enteredPath); - if(enteredPath.equals(currentPath)) ; - else if (isInvalidFileDirectory(testDirectory)) { - Toast.makeText(getActivity(), R.string.bad_directory, Toast.LENGTH_SHORT) - .show(); - } - else { - changeDirectory(testDirectory); - } - } - }); - - positiveButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Intent data = new Intent(); - data.setData(Uri.fromFile(currentDirectory)); - getActivity().setResult(Activity.RESULT_OK, data); - getActivity().finish(); - } - }); - - negativeButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - getActivity().setResult(Activity.RESULT_CANCELED, null); - getActivity().finish(); - } - }); - - upImage.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - changeDirectory(currentDirectory.getParentFile()); - } - }); - - directoryAdapter = new FileArrayAdapter(getActivity(), new ArrayList<File>()); - directoryAdapter.populateFileList(currentDirectory); - directoryListView.setAdapter(directoryAdapter); - directoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView<?> parent, View view, int position, long id) { - changeDirectory(directoryAdapter.getItem(position)); - } - }); - - return v; - } - - private void changeDirectory(File destination) { - if(destination == null) { - Toast.makeText(getActivity(), R.string.unable_to_go_further, Toast.LENGTH_SHORT) - .show(); - } else { - Fragment fragment = DirectoryBrowserFragment.newInstance(destination.toURI().toString()); - getActivity().getFragmentManager().beginTransaction() - .replace(R.id.fragment_container, fragment) - .addToBackStack(null) - .commit(); - } - } - - private void setupCurrentDirectory(String initialPathURI) { - File initialDirectory = null; - if(initialPathURI != null && !initialPathURI.isEmpty()) { - initialDirectory = IOUtils.getFileFromURIString(initialPathURI); - } - - if(isInvalidFileDirectory(initialDirectory)) { - initialDirectory = Environment.getExternalStorageDirectory(); - } - currentDirectory = initialDirectory; - } - - private boolean isInvalidFileDirectory(File f) { - return f == null || !f.exists() || !f.isDirectory() ||!f.canRead(); - } - - private class FileArrayAdapter extends ArrayAdapter<File> { - private Comparator<File> caseInsensitiveNaturalOrderComparator; - - public FileArrayAdapter(Context context, ArrayList<File> files) { - super(context, 0, files); - caseInsensitiveNaturalOrderComparator = new AlphabeticalFileComparator(); - } - - @Override - public View getView(int position, View convertView, ViewGroup parent) { - if (convertView == null) { - convertView = getActivity().getLayoutInflater() - .inflate(android.R.layout.simple_list_item_1, null); - } - - File f = this.getItem(position); - TextView tv = convertView.findViewById(android.R.id.text1); - tv.setText(f.getName()); - - return convertView; - } - - public void sortAlphabetically() { - this.sort(caseInsensitiveNaturalOrderComparator); - } - - public void populateFileList(File directory) { - for(File f : directory.listFiles()){ - if(f.isDirectory()){ - directoryAdapter.add(f); - } - } - directoryAdapter.sortAlphabetically(); - } - } - - private class AlphabeticalFileComparator implements Comparator<File> { - @Override - public int compare(File lhs, File rhs) { - String lhsName = lhs.getName(); - String rhsName = rhs.getName(); - - return lhsName.compareToIgnoreCase(rhsName); - } - } -} diff --git a/android/source/src/java/org/libreoffice/storage/external/ExternalFile.java b/android/source/src/java/org/libreoffice/storage/external/ExternalFile.java deleted file mode 100644 index aff33e4413ef..000000000000 --- a/android/source/src/java/org/libreoffice/storage/external/ExternalFile.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.libreoffice.storage.external; - -import android.content.Context; -import android.support.v4.provider.DocumentFile; -import android.util.Log; - -import org.libreoffice.storage.IFile; -import org.libreoffice.storage.IOUtils; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * Implementation of IFile for the external file system, for Android 4.4+ - * - * Uses the DocumentFile class. - * - * The DocumentFile class obfuscates the path of the files it wraps, - * preventing usage of LOK's documentLoad method. A copy of the DocumentFile's contents - * will be created in the cache when files are opened, allowing use of documentLoad. - */ -public class ExternalFile implements IFile{ - private final static String LOGTAG = "ExternalFile"; - - private ExtsdDocumentsProvider provider; - private DocumentFile docFile; - private File duplicateFile; - private Context context; - - public ExternalFile(ExtsdDocumentsProvider provider, DocumentFile docFile, Context context) { - this.provider = provider; - this.context = context; - this.docFile = docFile; - } - - @Override - public URI getUri() { - try{ - return new URI(docFile.toString()); - } catch (URISyntaxException e) { - Log.e(LOGTAG, e.getMessage(), e.getCause()); - return null; - } - } - - @Override - public String getName() { - return docFile.getName(); - } - - @Override - public boolean isDirectory() { - return docFile.isDirectory(); - } - - @Override - public long getSize() { - return docFile.length(); - } - - @Override - public Date getLastModified() { - return new Date(docFile.lastModified()); - } - - @Override - public List<IFile> listFiles() { - List<IFile> children = new ArrayList<IFile>(); - for (DocumentFile child : docFile.listFiles()) { - children.add(new ExternalFile(provider, child, context)); - } - return children; - } - - @Override - public List<IFile> listFiles(FileFilter filter) { - File file; - try{ - List<IFile> children = new ArrayList<IFile>(); - for (DocumentFile child : docFile.listFiles()) { - file = new File(new URI(child.getUri().toString())); - if(filter.accept(file)) - children.add(new ExternalFile(provider, child, context)); - } - return children; - - }catch (Exception e){ - e.printStackTrace(); - } - /* if something goes wrong */ - return listFiles(); - - } - - @Override - public IFile getParent(Context context) { - // this is the root node - if(docFile.getParentFile() == null) return null; - - return new ExternalFile(provider, docFile.getParentFile(), this.context); - } - - @Override - public File getDocument() { - if(isDirectory()) { - return null; - } else { - duplicateFile = duplicateInCache(); - return duplicateFile; - } - } - - private File duplicateInCache() { - try{ - InputStream istream = context.getContentResolver(). - openInputStream(docFile.getUri()); - - File storageFolder = provider.getCacheDir(); - File fileCopy = new File(storageFolder, docFile.getName()); - OutputStream ostream = new FileOutputStream(fileCopy); - - IOUtils.copy(istream, ostream); - return fileCopy; - } catch (Exception e) { - Log.e(LOGTAG, e.getMessage(), e.getCause()); - return null; - } - } - - @Override - public void saveDocument(File file) { - try{ - OutputStream ostream = context.getContentResolver(). - openOutputStream(docFile.getUri()); - InputStream istream = new FileInputStream(file); - - IOUtils.copy(istream, ostream); - - } catch (Exception e) { - Log.e(LOGTAG, e.getMessage(), e.getCause()); - } - } - - @Override - public boolean equals(Object object) { - if (this == object) - return true; - if (!(object instanceof ExternalFile)) - return false; - ExternalFile file = (ExternalFile) object; - return file.getUri().equals(getUri()); - } - -} diff --git a/android/source/src/java/org/libreoffice/storage/external/ExtsdDocumentsProvider.java b/android/source/src/java/org/libreoffice/storage/external/ExtsdDocumentsProvider.java deleted file mode 100644 index e45929374bbd..000000000000 --- a/android/source/src/java/org/libreoffice/storage/external/ExtsdDocumentsProvider.java +++ /dev/null @@ -1,175 +0,0 @@ -package org.libreoffice.storage.external; - -import android.Manifest; -import android.content.Context; -import android.content.SharedPreferences; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.os.Build; -import android.os.Environment; -import android.preference.PreferenceManager; -import android.support.v4.content.ContextCompat; -import android.support.v4.provider.DocumentFile; -import android.util.Log; - -import org.libreoffice.R; -import org.libreoffice.storage.DocumentProviderSettingsActivity; -import org.libreoffice.storage.IFile; - -import java.io.File; -import java.net.URI; - -/** - * Implementation of IDocumentProvider for the external file system, for android 4.4+ - * - * The DocumentFile class is required when accessing files in external storage - * for Android 4.4+. The ExternalFile class is used to handle this. - * - * Android 4.4 & 5+ use different types of root directory paths, - * 5 using a DirectoryTree Uri and 4.4 using a normal File path. - * As such, different methods are required to obtain the rootDirectory IFile. - * 4.4 has to guess the location of the rootDirectory as well. - */ -public class ExtsdDocumentsProvider implements IExternalDocumentProvider, - OnSharedPreferenceChangeListener{ - private static final String LOGTAG = ExtsdDocumentsProvider.class.getSimpleName(); - - private int id; - private File cacheDir; - private String rootPathURI; - - public ExtsdDocumentsProvider(int id, Context context) { - this.id = id; - setupRootPathUri(context); - setupCache(context); - } - - private void setupRootPathUri(Context context) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - rootPathURI = preferences.getString( - DocumentProviderSettingsActivity.KEY_PREF_EXTERNAL_SD_PATH_URI, guessRootURI(context)); - } - - public String guessRootURI(Context context) { - // TODO: unfortunately the getExternalFilesDirs function relies on devices to actually - // follow guidelines re external storage. Of course device manufacturers don't and as such - // you cannot rely on it returning the actual paths (neither the compat, nor the native variant) - File[] possibleRemovables = ContextCompat.getExternalFilesDirs(context,null); - // the primary dir that is already covered by the "LocalDocumentsProvider" - // might be emulated/part of internal memory or actual SD card - // TODO: change to not confuse android's "external storage" with "expandable storage" - String primaryExternal = Environment.getExternalStorageDirectory().getAbsolutePath(); - - for (File option: possibleRemovables) { - // Returned paths may be null if a storage device is unavailable. - if (null == option) { - Log.w(LOGTAG,"path was a null option :-/"); continue; } - String optionPath = option.getAbsolutePath(); - if(optionPath.contains(primaryExternal)) { - Log.v(LOGTAG, "did get file path - but is same as primary storage ("+ primaryExternal +")"); - continue; - } - - return option.toURI().toString(); - } - - // TODO: do some manual probing of possible directories (/storage/sdcard1 and similar) - Log.i(LOGTAG, "no secondary storage reported"); - return null; - } - - private void setupCache(Context context) { - // TODO: probably we should do smarter cache management - cacheDir = new File(context.getExternalCacheDir(), "externalFiles"); - if (cacheDir.exists()) { - deleteRecursive(cacheDir); - } - cacheDir.mkdirs(); - } - - private static void deleteRecursive(File file) { - if (file.isDirectory()) { - for (File child : file.listFiles()) - deleteRecursive(child); - } - file.delete(); - } - - public File getCacheDir() { - return cacheDir; - } - - @Override - public IFile getRootDirectory(Context context) { - if(android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { - return android4RootDirectory(context); - } else { - return android5RootDirectory(context); - } - } - - private ExternalFile android4RootDirectory(Context context) { - try{ - File f = new File(new URI(rootPathURI)); - return new ExternalFile(this, DocumentFile.fromFile(f), context); - } catch (Exception e) { - //invalid rootPathURI - throw buildRuntimeExceptionForInvalidFileURI(context); - } - } - - private ExternalFile android5RootDirectory(Context context) { - try { - return new ExternalFile(this, - DocumentFile.fromTreeUri(context, Uri.parse(rootPathURI)), - context); - } catch (Exception e) { - //invalid rootPathURI - throw buildRuntimeExceptionForInvalidFileURI(context); - } - } - - private RuntimeException buildRuntimeExceptionForInvalidFileURI(Context context) { - // ToDo: discarding the original exception / catch-all handling is bad style - return new RuntimeException(context.getString(R.string.ext_document_provider_error)); - } - - @Override - public IFile createFromUri(Context context, URI javaURI) { - //TODO: refactor when new DocumentFile API exist - //uri must be of a DocumentFile file, not directory. - Uri androidUri = Uri.parse(javaURI.toString()); - return new ExternalFile(this, - DocumentFile.fromSingleUri(context, androidUri), - context); - } - - @Override - public int getNameResource() { - return R.string.external_sd_file_system; - } - - @Override - public int getId() { - return id; - } - - @Override - public boolean checkProviderAvailability(Context context) { - // too many devices (or I am just unlucky) don't report the mounted state properly, and other - // devices also consider dedicated part of internal storage to be "mounted" so cannot use - // getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && isExternalStorageRemovable() - // but they refer to the primary external storage anyway, so what currently is covered by the - // "LocalDocumentsProvider" - return rootPathURI!=null && ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { - if (key.equals(DocumentProviderSettingsActivity.KEY_PREF_EXTERNAL_SD_PATH_URI)) { - rootPathURI = preferences.getString(key, ""); - } - } - -} diff --git a/android/source/src/java/org/libreoffice/storage/external/IExternalDocumentProvider.java b/android/source/src/java/org/libreoffice/storage/external/IExternalDocumentProvider.java deleted file mode 100644 index a439417b60cd..000000000000 --- a/android/source/src/java/org/libreoffice/storage/external/IExternalDocumentProvider.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.libreoffice.storage.external; - -import android.content.Context; - -import org.libreoffice.storage.IDocumentProvider; - - -/** - * Interface for external document providers. - */ -public interface IExternalDocumentProvider extends IDocumentProvider { - - /** - * Used to obtain the default directory to display when - * browsing using the internal DirectoryBrowser. - * - * @return a guess of the root file's URI. - * @param context - */ - String guessRootURI(Context context); - -} diff --git a/android/source/src/java/org/libreoffice/storage/external/OTGDocumentsProvider.java b/android/source/src/java/org/libreoffice/storage/external/OTGDocumentsProvider.java deleted file mode 100644 index 4341bc3541e6..000000000000 --- a/android/source/src/java/org/libreoffice/storage/external/OTGDocumentsProvider.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.libreoffice.storage.external; - -import android.content.Context; -import android.content.SharedPreferences; -import android.content.pm.PackageManager; -import android.preference.PreferenceManager; -import android.util.Log; - -import org.libreoffice.R; -import org.libreoffice.storage.DocumentProviderSettingsActivity; -import org.libreoffice.storage.IFile; -import org.libreoffice.storage.IOUtils; -import org.libreoffice.storage.local.LocalFile; - -import java.io.File; -import java.net.URI; - -/** - * TODO: OTG currently uses LocalFile. Change to an IFile that handles abrupt OTG unmounting - */ -public class OTGDocumentsProvider implements IExternalDocumentProvider, - SharedPreferences.OnSharedPreferenceChangeListener { - - private static final String LOGTAG = OTGDocumentsProvider.class.getSimpleName(); - - private String rootPathURI; - private int id; - - public OTGDocumentsProvider(int id, Context context) { - this.id = id; - setupRootPath(context); - } - - private void setupRootPath(Context context) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - rootPathURI = preferences.getString( - DocumentProviderSettingsActivity.KEY_PREF_OTG_PATH_URI, ""); - } - - @Override - public IFile createFromUri(Context context, URI uri) { - return new LocalFile(uri); - } - - @Override - public int getNameResource() { - return R.string.otg_file_system; - } - - @Override - public int getId() { - return id; - } - - @Override - public IFile getRootDirectory(Context context) { - // TODO: handle this with more fine-grained exceptions - if(rootPathURI.equals("")) { - Log.e(LOGTAG, "rootPathURI is empty"); - throw new RuntimeException(context.getString(R.string.ext_document_provider_error)); - } - - File f = IOUtils.getFileFromURIString(rootPathURI); - if(IOUtils.isInvalidFile(f)) { - Log.e(LOGTAG, "rootPathURI is invalid - missing device?"); - throw new RuntimeException(context.getString(R.string.otg_missing_error)); - } - - return new LocalFile(f); - } - - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - if (key.equals(DocumentProviderSettingsActivity.KEY_PREF_OTG_PATH_URI)) { - rootPathURI = sharedPreferences.getString(key, ""); - } - } - - @Override - public String guessRootURI(Context context) { - return ""; - } - - @Override - public boolean checkProviderAvailability(Context context) { - // check if system supports USB Host - return rootPathURI.length()>0 && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST); - } -} diff --git a/android/source/src/java/org/libreoffice/storage/local/LocalDocumentsDirectoryProvider.java b/android/source/src/java/org/libreoffice/storage/local/LocalDocumentsDirectoryProvider.java deleted file mode 100644 index 15522e93a45e..000000000000 --- a/android/source/src/java/org/libreoffice/storage/local/LocalDocumentsDirectoryProvider.java +++ /dev/null @@ -1,73 +0,0 @@ -/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.libreoffice.storage.local; - -import java.io.File; - -import org.libreoffice.storage.IFile; -import org.libreoffice.R; - -import android.Manifest; -import android.content.Context; -import android.content.pm.PackageManager; -import android.os.Build; -import android.os.Environment; -import android.support.v4.content.ContextCompat; -import android.util.Log; - -/** - * A convenience IDocumentProvider to browse the /sdcard/Documents directory. - * - * Extends LocalDocumentsProvider to overwrite getRootDirectory and set it to - * /sdcard/Documents. Most documents will probably be stored there so there is - * no need for the user to browse the filesystem from the root every time. - */ -public class LocalDocumentsDirectoryProvider extends LocalDocumentsProvider { - - public LocalDocumentsDirectoryProvider(int id) { - super(id); - } - - private static File getDocumentsDir() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - // DIRECTORY_DOCUMENTS is 19 or later only - return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS); - } else { - return new File(Environment.getExternalStorageDirectory() + "/Documents"); - } - } - - @Override - public IFile getRootDirectory(Context context) { - File documentsDirectory = getDocumentsDir(); - if (!documentsDirectory.exists()) { - if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { - if(!documentsDirectory.mkdirs()) { - // fallback to the toplevel dir - might be due to the dir not mounted/used as USB-Mass-Storage or similar - // TODO: handle unavailability of the storage/failure of the mkdir properly - Log.e("LocalDocumentsProvider", "not sure how we ended up here - if we have read permissions to use it in the first place, we also should have the write-permissions.."); - documentsDirectory = Environment.getExternalStorageDirectory(); - } - } - } - return new LocalFile(documentsDirectory); - } - - @Override - public int getNameResource() { - return R.string.local_documents; - } - - @Override - public boolean checkProviderAvailability(Context context) { - File documentsDirectory = getDocumentsDir(); - return documentsDirectory.exists() && ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; - } -} diff --git a/android/source/src/java/org/libreoffice/storage/local/LocalDocumentsProvider.java b/android/source/src/java/org/libreoffice/storage/local/LocalDocumentsProvider.java deleted file mode 100644 index 1a10fad424db..000000000000 --- a/android/source/src/java/org/libreoffice/storage/local/LocalDocumentsProvider.java +++ /dev/null @@ -1,60 +0,0 @@ -/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.libreoffice.storage.local; - -import java.net.URI; - -import org.libreoffice.storage.IDocumentProvider; -import org.libreoffice.storage.IFile; - -import org.libreoffice.R; - -import android.Manifest; -import android.content.Context; -import android.content.pm.PackageManager; -import android.os.Environment; -import android.support.v4.content.ContextCompat; - -/** - * Implementation of IDocumentProvider for the local file system. - */ -public class LocalDocumentsProvider implements IDocumentProvider { - - private int id; - - public LocalDocumentsProvider(int id) { - this.id = id; - } - - @Override - public IFile getRootDirectory(Context context) { - return new LocalFile(Environment.getExternalStorageDirectory()); - } - - @Override - public IFile createFromUri(Context context, URI uri) { - return new LocalFile(uri); - } - - @Override - public int getNameResource() { - return R.string.local_file_system; - } - - @Override - public int getId() { - return id; - } - - @Override - public boolean checkProviderAvailability(Context context) { - return ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED; - } -} diff --git a/android/source/src/java/org/libreoffice/storage/local/LocalFile.java b/android/source/src/java/org/libreoffice/storage/local/LocalFile.java deleted file mode 100644 index 4ff5bbf119f4..000000000000 --- a/android/source/src/java/org/libreoffice/storage/local/LocalFile.java +++ /dev/null @@ -1,103 +0,0 @@ -/* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* - * This file is part of the LibreOffice project. - * - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -package org.libreoffice.storage.local; - -import android.content.Context; - -import java.io.File; -import java.io.FileFilter; -import java.net.URI; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.libreoffice.storage.IFile; - -/** - * Implementation of IFile for the local file system. - */ -public class LocalFile implements IFile { - - private File file; - - public LocalFile(File file) { - this.file = file; - } - - public LocalFile(URI uri) { - this.file = new File(uri); - } - - public URI getUri() { - return file.toURI(); - } - - public String getName() { - return file.getName(); - } - - @Override - public boolean isDirectory() { - return file.isDirectory(); - } - - @Override - public long getSize() { - return file.length(); - } - - @Override - public Date getLastModified() { - return new Date(file.lastModified()); - } - - @Override - public List<IFile> listFiles() { - List<IFile> children = new ArrayList<IFile>(); - for (File child : file.listFiles()) { - children.add(new LocalFile(child)); - } - return children; - } - - @Override - public List<IFile> listFiles(FileFilter filter) { - List<IFile> children = new ArrayList<IFile>(); - for (File child : file.listFiles(filter)) { - children.add(new LocalFile(child)); - } - return children; - } - - @Override - public IFile getParent(Context context) { - return new LocalFile(file.getParentFile()); - } - - @Override - public File getDocument() { - return file; - } - - @Override - public boolean equals(Object object) { - if (this == object) - return true; - if (!(object instanceof LocalFile)) - return false; - LocalFile file = (LocalFile) object; - return file.getUri().equals(getUri()); - } - - @Override - public void saveDocument(File file) { - // do nothing; file is local - } -} diff --git a/android/source/src/java/org/libreoffice/storage/owncloud/OwnCloudFile.java b/android/source/src/java/org/libreoffice/storage/owncloud/OwnCloudFile.java deleted file mode 100644 index fa74a54b08e2..000000000000 --- a/android/source/src/java/org/libreoffice/storage/owncloud/OwnCloudFile.java +++ /dev/null @@ -1,178 +0,0 @@ -package org.libreoffice.storage.owncloud; - -import android.content.Context; - -import java.io.File; -import java.io.FileFilter; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.libreoffice.storage.IFile; - -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.resources.files.ChunkedUploadRemoteFileOperation; -import com.owncloud.android.lib.resources.files.DownloadRemoteFileOperation; -import com.owncloud.android.lib.resources.files.ReadRemoteFolderOperation; -import com.owncloud.android.lib.resources.files.RemoteFile; -import com.owncloud.android.lib.resources.files.UploadRemoteFileOperation; - -/** - * Implementation of IFile for ownCloud servers. - */ -public class OwnCloudFile implements IFile { - - private OwnCloudProvider provider; - private RemoteFile file; - - private String name; - private String parentPath; - - protected OwnCloudFile(OwnCloudProvider provider, RemoteFile file) { - this.provider = provider; - this.file = file; - - // get name and parent from path - File localFile = new File(file.getRemotePath()); - this.name = localFile.getName(); - this.parentPath = localFile.getParent(); - } - - @Override - public URI getUri(){ - - try{ - return URI.create(URLEncoder.encode(file.getRemotePath(),"UTF-8")); - }catch(UnsupportedEncodingException e){ - e.printStackTrace(); - } - - return null; - } - - @Override - public String getName() { - return name; - } - - @Override - public boolean isDirectory() { - return file.getMimeType().equals("DIR"); - } - - @Override - public long getSize() { - return file.getLength(); - } - - @Override - public Date getLastModified() { - return new Date(file.getModifiedTimestamp()); - } - - @Override - public List<IFile> listFiles() { - List<IFile> children = new ArrayList<IFile>(); - if (isDirectory()) { - ReadRemoteFolderOperation refreshOperation = new ReadRemoteFolderOperation( - file.getRemotePath()); - RemoteOperationResult result = refreshOperation.execute(provider - .getClient()); - if (!result.isSuccess()) { - throw provider.buildRuntimeExceptionForResultCode(result.getCode()); - } - for (Object obj : result.getData()) { - RemoteFile child = (RemoteFile) obj; - if (!child.getRemotePath().equals(file.getRemotePath())) - children.add(new OwnCloudFile(provider, child)); - } - } - return children; - } - - @Override - public List<IFile> listFiles(FileFilter filter) { - List<IFile> children = new ArrayList<IFile>(); - if (isDirectory()) { - ReadRemoteFolderOperation refreshOperation = new ReadRemoteFolderOperation( - file.getRemotePath()); - RemoteOperationResult result = refreshOperation.execute(provider - .getClient()); - if (!result.isSuccess()) { - throw provider.buildRuntimeExceptionForResultCode(result.getCode()); - } - - for (Object obj : result.getData()) { - RemoteFile child = (RemoteFile) obj; - if (!child.getRemotePath().equals(file.getRemotePath())){ - OwnCloudFile ownCloudFile = new OwnCloudFile(provider, child); - if(!ownCloudFile.isDirectory()){ - File f = new File(provider.getCacheDir().getAbsolutePath(), - ownCloudFile.getName()); - if(filter.accept(f)) - children.add(ownCloudFile); - f.delete(); - }else{ - children.add(ownCloudFile); - } - } - } - } - return children; - } - - @Override - public IFile getParent(Context context) { - if (parentPath == null) - // this is the root node - return null; - - return provider.createFromUri(context, URI.create(parentPath)); - } - - @Override - public File getDocument() { - if (isDirectory()) { - return null; - } - File downFolder = provider.getCacheDir(); - DownloadRemoteFileOperation operation = new DownloadRemoteFileOperation( - file.getRemotePath(), downFolder.getAbsolutePath()); - RemoteOperationResult result = operation.execute(provider.getClient()); - if (!result.isSuccess()) { - throw provider.buildRuntimeExceptionForResultCode(result.getCode()); - } - return new File(downFolder.getAbsolutePath() + file.getRemotePath()); - } - - @Override - public boolean equals(Object object) { - if (this == object) - return true; - if (!(object instanceof OwnCloudFile)) - return false; - OwnCloudFile file = (OwnCloudFile) object; - return file.getUri().equals(getUri()); - } - - @Override - public void saveDocument(File newFile) { - UploadRemoteFileOperation uploadOperation; - if (newFile.length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE) { - uploadOperation = new ChunkedUploadRemoteFileOperation( - newFile.getPath(), file.getRemotePath(), file.getMimeType()); - } else { - uploadOperation = new UploadRemoteFileOperation(newFile.getPath(), - file.getRemotePath(), file.getMimeType()); - } - - RemoteOperationResult result = uploadOperation.execute(provider - .getClient()); - if (!result.isSuccess()) { - throw provider.buildRuntimeExceptionForResultCode(result.getCode()); - } - } -} diff --git a/android/source/src/java/org/libreoffice/storage/owncloud/OwnCloudProvider.java b/android/source/src/java/org/libreoffice/storage/owncloud/OwnCloudProvider.java deleted file mode 100644 index 0852ab617660..000000000000 --- a/android/source/src/java/org/libreoffice/storage/owncloud/OwnCloudProvider.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.libreoffice.storage.owncloud; - -import java.io.File; -import java.net.URI; - -import org.libreoffice.R; -import org.libreoffice.storage.DocumentProviderSettingsActivity; -import org.libreoffice.storage.IDocumentProvider; -import org.libreoffice.storage.IFile; - -import android.content.Context; -import android.content.SharedPreferences; -import android.content.SharedPreferences.OnSharedPreferenceChangeListener; -import android.net.Uri; -import android.preference.PreferenceManager; - -import com.owncloud.android.lib.common.OwnCloudClient; -import com.owncloud.android.lib.common.OwnCloudClientFactory; -import com.owncloud.android.lib.common.OwnCloudCredentialsFactory; -import com.owncloud.android.lib.common.operations.RemoteOperationResult; -import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.lib.resources.files.FileUtils; -import com.owncloud.android.lib.resources.files.ReadRemoteFileOperation; -import com.owncloud.android.lib.resources.files.RemoteFile; - - -/** - * Implementation of IDocumentProvider for ownCloud servers. - */ -public class OwnCloudProvider implements IDocumentProvider, - OnSharedPreferenceChangeListener { - - private int id; - - private Context context; - private OwnCloudClient client; - private File cacheDir; - - private String serverUrl; - private String userName; - private String password; - private RemoteOperationResult result; - - public OwnCloudProvider(int id, Context context) { - this.id = id; - this.context = context; - - // read preferences - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - serverUrl = preferences.getString( - DocumentProviderSettingsActivity.KEY_PREF_OWNCLOUD_SERVER, ""); - userName = preferences.getString( - DocumentProviderSettingsActivity.KEY_PREF_OWNCLOUD_USER_NAME, ""); - password = preferences.getString( - DocumentProviderSettingsActivity.KEY_PREF_OWNCLOUD_PASSWORD, ""); - - setupClient(); - - // make sure cache directory exists, and clear it - // TODO: probably we should do smarter cache management - cacheDir = new File(context.getCacheDir(), "ownCloud"); - if (cacheDir.exists()) { - deleteRecursive(cacheDir); - } - cacheDir.mkdirs(); - } - - private void setupClient() { - Uri serverUri = Uri.parse(serverUrl); - client = OwnCloudClientFactory.createOwnCloudClient(serverUri, context, - true); - client.setCredentials(OwnCloudCredentialsFactory.newBasicCredentials( - userName, password)); - } - - @Override - public IFile getRootDirectory(Context context) { - return createFromUri(context, URI.create(FileUtils.PATH_SEPARATOR)); - } - - @Override - public IFile createFromUri(Context context, URI uri) { - if(serverUrl != "" || userName != "" || password != ""){ - ReadRemoteFileOperation refreshOperation = new ReadRemoteFileOperation( - uri.getPath()); - this.result = refreshOperation.execute(client); - if (!result.isSuccess()) { - throw buildRuntimeExceptionForResultCode(result.getCode()); - } - if (result.getData().size() > 0) { - return new OwnCloudFile(this, (RemoteFile) result.getData().get(0)); - } - } else { - throw buildRuntimeExceptionForResultCode(ResultCode.WRONG_CONNECTION); - } - - return null; - } - - @Override - public int getNameResource() { - return R.string.owncloud; - } - - /** - * Used by OwnCloudFiles to get a configured client to run their own - * operations. - * - * @return configured OwnCloudClient. - */ - protected OwnCloudClient getClient() { - return client; - } - - /** - * Used by OwnCloudFiles to get the cache directory they should download - * files to. - * - * @return cache directory. - */ - protected File getCacheDir() { - return cacheDir; - } - - /** - * Build the proper RuntimeException for some error result. - * - * @param code Result code got from some RemoteOperationResult. - * @return exception with the proper internationalized error message. - */ - protected RuntimeException buildRuntimeExceptionForResultCode(ResultCode code) { - int errorMessage; - switch (code) { - case WRONG_CONNECTION: // SocketException - case FILE_NOT_FOUND: // HTTP 404 - errorMessage = R.string.owncloud_wrong_connection; - break; - case UNAUTHORIZED: // wrong user/pass - errorMessage = R.string.owncloud_unauthorized; - break; - default: - errorMessage = R.string.owncloud_unspecified_error; - break; - } - return new RuntimeException(context.getString(errorMessage)); - } - - /** - * Deletes files and recursively deletes directories. - * - * @param file - * File or directory to be deleted. - */ - private static void deleteRecursive(File file) { - if (file.isDirectory()) { - for (File child : file.listFiles()) - deleteRecursive(child); - } - file.delete(); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, - String key) { - boolean changed = false; - if (key.equals(DocumentProviderSettingsActivity.KEY_PREF_OWNCLOUD_SERVER)) { - serverUrl = preferences.getString(key, ""); - changed = true; - } - else if (key.equals(DocumentProviderSettingsActivity.KEY_PREF_OWNCLOUD_USER_NAME)) { - userName = preferences.getString(key, ""); - changed = true; - } - else if (key.equals(DocumentProviderSettingsActivity.KEY_PREF_OWNCLOUD_PASSWORD)) { - password = preferences.getString(key, ""); - changed = true; - } - - if (changed) - setupClient(); - } - - @Override - public int getId() { - return id; - } - - @Override - public boolean checkProviderAvailability(Context context) { - return client != null; - } -} |