Move import async tasks and ImportHelper to separate package

This commit is contained in:
Vitaliy 2020-10-06 19:48:33 +03:00
parent 38ba94ee1c
commit 4774382258
19 changed files with 858 additions and 582 deletions

View file

@ -99,7 +99,7 @@ import net.osmand.plus.firstusage.FirstUsageWelcomeFragment;
import net.osmand.plus.firstusage.FirstUsageWizardFragment; import net.osmand.plus.firstusage.FirstUsageWizardFragment;
import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.AndroidUiHelper;
import net.osmand.plus.helpers.DiscountHelper; import net.osmand.plus.helpers.DiscountHelper;
import net.osmand.plus.helpers.ImportHelper; import net.osmand.plus.importfiles.ImportHelper;
import net.osmand.plus.helpers.IntentHelper; import net.osmand.plus.helpers.IntentHelper;
import net.osmand.plus.helpers.LockHelper; import net.osmand.plus.helpers.LockHelper;
import net.osmand.plus.helpers.LockHelper.LockUIAdapter; import net.osmand.plus.helpers.LockHelper.LockUIAdapter;

View file

@ -13,7 +13,7 @@ import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem;
import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerHalfItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerHalfItem;
import net.osmand.plus.base.bottomsheetmenu.simpleitems.ShortDescriptionItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.ShortDescriptionItem;
import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem;
import net.osmand.plus.helpers.ImportHelper; import net.osmand.plus.importfiles.ImportHelper;
public class ImportGpxBottomSheetDialogFragment extends MenuBottomSheetDialogFragment { public class ImportGpxBottomSheetDialogFragment extends MenuBottomSheetDialogFragment {

View file

@ -0,0 +1,45 @@
package net.osmand.plus.importfiles;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.AndroidUtils;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import java.lang.ref.WeakReference;
abstract class BaseImportAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
protected OsmandApplication app;
protected WeakReference<FragmentActivity> activityRef;
protected ProgressDialog progress;
public BaseImportAsyncTask(@NonNull FragmentActivity activity) {
app = (OsmandApplication) activity.getApplicationContext();
activityRef = new WeakReference<>(activity);
}
@Override
protected void onPreExecute() {
showProgress();
}
protected void showProgress() {
FragmentActivity activity = activityRef.get();
if (AndroidUtils.isActivityNotDestroyed(activity)) {
String title = app.getString(R.string.loading_smth, "");
progress = ProgressDialog.show(activity, title, app.getString(R.string.loading_data));
}
}
protected void hideProgress() {
FragmentActivity activity = activityRef.get();
if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) {
progress.dismiss();
}
}
}

View file

@ -0,0 +1,59 @@
package net.osmand.plus.importfiles;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.GPXUtilities;
import net.osmand.GPXUtilities.GPXFile;
import net.osmand.data.FavouritePoint;
import net.osmand.plus.FavouritesDbHelper;
import net.osmand.plus.R;
import java.util.List;
import static net.osmand.plus.importfiles.ImportHelper.asFavourites;
import static net.osmand.plus.myplaces.FavoritesActivity.FAV_TAB;
import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID;
class FavoritesImportTask extends BaseImportAsyncTask<Void, Void, GPXFile> {
private GPXFile gpxFile;
private String fileName;
private boolean forceImportFavourites;
public FavoritesImportTask(@NonNull FragmentActivity activity, @NonNull GPXFile gpxFile,
@NonNull String fileName, boolean forceImportFavourites) {
super(activity);
this.gpxFile = gpxFile;
this.fileName = fileName;
this.forceImportFavourites = forceImportFavourites;
}
@Override
protected GPXFile doInBackground(Void... nothing) {
List<FavouritePoint> favourites = asFavourites(app, gpxFile.getPoints(), fileName, forceImportFavourites);
FavouritesDbHelper favoritesHelper = app.getFavorites();
for (FavouritePoint favourite : favourites) {
favoritesHelper.deleteFavourite(favourite, false);
favoritesHelper.addFavourite(favourite, false);
}
favoritesHelper.sortAll();
favoritesHelper.saveCurrentPointsIntoFile();
return null;
}
@Override
protected void onPostExecute(GPXUtilities.GPXFile result) {
hideProgress();
FragmentActivity activity = activityRef.get();
if (activity != null) {
app.showToastMessage(R.string.fav_imported_sucessfully);
Intent newIntent = new Intent(activity, app.getAppCustomization().getFavoritesActivity());
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.putExtra(TAB_ID, FAV_TAB);
activity.startActivity(newIntent);
}
}
}

View file

@ -0,0 +1,59 @@
package net.osmand.plus.importfiles;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.GPXUtilities;
import net.osmand.GPXUtilities.GPXFile;
import net.osmand.util.Algorithms;
import java.io.FileNotFoundException;
import java.io.InputStream;
class GpxImportTask extends BaseImportAsyncTask<Void, Void, GPXFile> {
private ImportHelper importHelper;
private Uri gpxFile;
private String fileName;
private boolean save;
private boolean useImportDir;
private boolean showInDetailsActivity;
public GpxImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity,
@NonNull Uri gpxFile, @NonNull String fileName, boolean save, boolean useImportDir,
boolean showInDetailsActivity) {
super(activity);
this.importHelper = importHelper;
this.gpxFile = gpxFile;
this.fileName = fileName;
this.save = save;
this.useImportDir = useImportDir;
this.showInDetailsActivity = showInDetailsActivity;
}
@Override
protected GPXFile doInBackground(Void... nothing) {
InputStream is = null;
try {
is = app.getContentResolver().openInputStream(gpxFile);
if (is != null) {
return GPXUtilities.loadGPXFile(is);
}
} catch (FileNotFoundException e) {
//
} catch (SecurityException e) {
ImportHelper.log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
}
return null;
}
@Override
protected void onPostExecute(GPXUtilities.GPXFile result) {
hideProgress();
importHelper.handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity);
}
}

View file

@ -0,0 +1,83 @@
package net.osmand.plus.importfiles;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.GPXUtilities;
import net.osmand.GPXUtilities.GPXFile;
import net.osmand.util.Algorithms;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static net.osmand.plus.importfiles.KmlImportTask.loadGpxFromKml;
class GpxOrFavouritesImportTask extends BaseImportAsyncTask<Void, Void, GPXFile> {
private ImportHelper importHelper;
private Uri fileUri;
private String fileName;
private boolean save;
private boolean useImportDir;
private boolean forceImportFavourites;
private boolean forceImportGpx;
public GpxOrFavouritesImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity,
@NonNull Uri fileUri, String fileName, boolean save, boolean useImportDir,
boolean forceImportFavourites, boolean forceImportGpx) {
super(activity);
this.importHelper = importHelper;
this.fileUri = fileUri;
this.fileName = fileName;
this.save = save;
this.useImportDir = useImportDir;
this.forceImportFavourites = forceImportFavourites;
this.forceImportGpx = forceImportGpx;
}
@Override
protected GPXFile doInBackground(Void... nothing) {
InputStream is = null;
ZipInputStream zis = null;
try {
is = app.getContentResolver().openInputStream(fileUri);
if (is != null) {
if (fileName != null && fileName.endsWith(ImportHelper.KML_SUFFIX)) {
return loadGpxFromKml(is);
} else if (fileName != null && fileName.endsWith(ImportHelper.KMZ_SUFFIX)) {
try {
zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.getName().endsWith(ImportHelper.KML_SUFFIX)) {
return loadGpxFromKml(zis);
}
}
} catch (Exception e) {
return null;
}
} else {
return GPXUtilities.loadGPXFile(is);
}
}
} catch (FileNotFoundException e) {
//
} catch (SecurityException e) {
ImportHelper.log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
Algorithms.closeStream(zis);
}
return null;
}
@Override
protected void onPostExecute(final GPXUtilities.GPXFile result) {
hideProgress();
importHelper.importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx);
}
}

View file

@ -1,7 +1,5 @@
package net.osmand.plus.helpers; package net.osmand.plus.importfiles;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.database.Cursor; import android.database.Cursor;
@ -17,65 +15,47 @@ import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import net.osmand.AndroidUtils;
import net.osmand.CallbackWithObject; import net.osmand.CallbackWithObject;
import net.osmand.GPXUtilities; import net.osmand.GPXUtilities;
import net.osmand.GPXUtilities.GPXFile; import net.osmand.GPXUtilities.GPXFile;
import net.osmand.GPXUtilities.WptPt; import net.osmand.GPXUtilities.WptPt;
import net.osmand.IProgress;
import net.osmand.IndexConstants; import net.osmand.IndexConstants;
import net.osmand.PlatformUtil; import net.osmand.PlatformUtil;
import net.osmand.data.FavouritePoint; import net.osmand.data.FavouritePoint;
import net.osmand.data.FavouritePoint.BackgroundType; import net.osmand.data.FavouritePoint.BackgroundType;
import net.osmand.plus.AppInitializer; import net.osmand.plus.AppInitializer;
import net.osmand.plus.CustomOsmandPlugin;
import net.osmand.plus.FavouritesDbHelper;
import net.osmand.plus.GPXDatabase.GpxDataItem; import net.osmand.plus.GPXDatabase.GpxDataItem;
import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R; import net.osmand.plus.R;
import net.osmand.plus.activities.ActivityResultListener; import net.osmand.plus.activities.ActivityResultListener;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.activities.TrackActivity; import net.osmand.plus.activities.TrackActivity;
import net.osmand.plus.dialogs.ImportGpxBottomSheetDialogFragment; import net.osmand.plus.dialogs.ImportGpxBottomSheetDialogFragment;
import net.osmand.plus.measurementtool.MeasurementToolFragment; import net.osmand.plus.measurementtool.MeasurementToolFragment;
import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin;
import net.osmand.plus.settings.backend.SettingsHelper; import net.osmand.plus.settings.backend.SettingsHelper;
import net.osmand.plus.settings.backend.SettingsHelper.CheckDuplicatesListener;
import net.osmand.plus.settings.backend.SettingsHelper.PluginSettingsItem;
import net.osmand.plus.settings.backend.SettingsHelper.ProfileSettingsItem;
import net.osmand.plus.settings.backend.SettingsHelper.SettingsCollectListener;
import net.osmand.plus.settings.backend.SettingsHelper.SettingsImportListener;
import net.osmand.plus.settings.backend.SettingsHelper.SettingsItem; import net.osmand.plus.settings.backend.SettingsHelper.SettingsItem;
import net.osmand.plus.settings.fragments.ImportSettingsFragment;
import net.osmand.plus.views.OsmandMapTileView; import net.osmand.plus.views.OsmandMapTileView;
import net.osmand.router.RoutingConfiguration;
import net.osmand.util.Algorithms; import net.osmand.util.Algorithms;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static android.app.Activity.RESULT_OK; import static android.app.Activity.RESULT_OK;
import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT;
import static net.osmand.IndexConstants.GPX_FILE_EXT; import static net.osmand.IndexConstants.GPX_FILE_EXT;
import static net.osmand.IndexConstants.GPX_INDEX_DIR;
import static net.osmand.IndexConstants.OSMAND_SETTINGS_FILE_EXT; import static net.osmand.IndexConstants.OSMAND_SETTINGS_FILE_EXT;
import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; import static net.osmand.IndexConstants.RENDERER_INDEX_EXT;
import static net.osmand.IndexConstants.ROUTING_FILE_EXT; import static net.osmand.IndexConstants.ROUTING_FILE_EXT;
@ -83,8 +63,6 @@ import static net.osmand.IndexConstants.SQLITE_CHART_FILE_EXT;
import static net.osmand.IndexConstants.SQLITE_EXT; import static net.osmand.IndexConstants.SQLITE_EXT;
import static net.osmand.IndexConstants.WPT_CHART_FILE_EXT; import static net.osmand.IndexConstants.WPT_CHART_FILE_EXT;
import static net.osmand.data.FavouritePoint.DEFAULT_BACKGROUND_TYPE; import static net.osmand.data.FavouritePoint.DEFAULT_BACKGROUND_TYPE;
import static net.osmand.plus.AppInitializer.loadRoutingFiles;
import static net.osmand.plus.myplaces.FavoritesActivity.FAV_TAB;
import static net.osmand.plus.myplaces.FavoritesActivity.GPX_TAB; import static net.osmand.plus.myplaces.FavoritesActivity.GPX_TAB;
import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID; import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID;
@ -124,6 +102,7 @@ public class ImportHelper {
public interface OnGpxImportCompleteListener { public interface OnGpxImportCompleteListener {
void onImportComplete(boolean success); void onImportComplete(boolean success);
void onSaveComplete(boolean success, GPXFile result); void onSaveComplete(boolean success, GPXFile result);
} }
@ -138,7 +117,7 @@ public class ImportHelper {
} }
public void handleContentImport(final Uri contentUri, Bundle extras, final boolean useImportDir) { public void handleContentImport(final Uri contentUri, Bundle extras, final boolean useImportDir) {
final String name = getNameFromContentUri(app, contentUri); String name = getNameFromContentUri(app, contentUri);
handleFileImport(contentUri, name, extras, useImportDir); handleFileImport(contentUri, name, extras, useImportDir);
} }
@ -156,7 +135,7 @@ public class ImportHelper {
public boolean handleGpxImport(final Uri contentUri, final boolean useImportDir, boolean showInDetailsActivity) { public boolean handleGpxImport(final Uri contentUri, final boolean useImportDir, boolean showInDetailsActivity) {
String name = getNameFromContentUri(app, contentUri); String name = getNameFromContentUri(app, contentUri);
boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(contentUri.getPath())); boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(contentUri.getPath()));
if (!isOsmandSubdir && name != null) { if (!isOsmandSubdir && name != null) {
String nameLC = name.toLowerCase(); String nameLC = name.toLowerCase();
if (nameLC.endsWith(GPX_FILE_EXT)) { if (nameLC.endsWith(GPX_FILE_EXT)) {
@ -180,7 +159,7 @@ public class ImportHelper {
String scheme = uri.getScheme(); String scheme = uri.getScheme();
boolean isFileIntent = "file".equals(scheme); boolean isFileIntent = "file".equals(scheme);
boolean isContentIntent = "content".equals(scheme); boolean isContentIntent = "content".equals(scheme);
boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(uri.getPath())); boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(uri.getPath()));
final boolean saveFile = !isFileIntent || !isOsmandSubdir; final boolean saveFile = !isFileIntent || !isOsmandSubdir;
String fileName = ""; String fileName = "";
if (isFileIntent) { if (isFileIntent) {
@ -193,7 +172,7 @@ public class ImportHelper {
public void handleFileImport(Uri intentUri, String fileName, Bundle extras, boolean useImportDir) { public void handleFileImport(Uri intentUri, String fileName, Bundle extras, boolean useImportDir) {
boolean isFileIntent = "file".equals(intentUri.getScheme()); boolean isFileIntent = "file".equals(intentUri.getScheme());
boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(intentUri.getPath())); boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(intentUri.getPath()));
boolean saveFile = !isFileIntent || !isOsmandSubdir; boolean saveFile = !isFileIntent || !isOsmandSubdir;
if (fileName == null) { if (fileName == null) {
@ -202,7 +181,7 @@ public class ImportHelper {
handleKmlImport(intentUri, fileName, saveFile, useImportDir); handleKmlImport(intentUri, fileName, saveFile, useImportDir);
} else if (fileName.endsWith(KMZ_SUFFIX)) { } else if (fileName.endsWith(KMZ_SUFFIX)) {
handleKmzImport(intentUri, fileName, saveFile, useImportDir); handleKmzImport(intentUri, fileName, saveFile, useImportDir);
} else if (fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) { } else if (fileName.endsWith(BINARY_MAP_INDEX_EXT)) {
handleObfImport(intentUri, fileName); handleObfImport(intentUri, fileName);
} else if (fileName.endsWith(SQLITE_EXT)) { } else if (fileName.endsWith(SQLITE_EXT)) {
handleSqliteTileImport(intentUri, fileName); handleSqliteTileImport(intentUri, fileName);
@ -221,9 +200,8 @@ public class ImportHelper {
public static String getNameFromContentUri(OsmandApplication app, Uri contentUri) { public static String getNameFromContentUri(OsmandApplication app, Uri contentUri) {
try { try {
final String name; String name;
final Cursor returnCursor = app.getContentResolver().query(contentUri, Cursor returnCursor = app.getContentResolver().query(contentUri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null);
new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null);
if (returnCursor != null && returnCursor.moveToFirst()) { if (returnCursor != null && returnCursor.moveToFirst()) {
int columnIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); int columnIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (columnIndex != -1) { if (columnIndex != -1) {
@ -244,251 +222,52 @@ public class ImportHelper {
} }
} }
@SuppressLint("StaticFieldLeak") private void handleGpxImport(Uri gpxFile, String fileName, boolean save, boolean useImportDir, boolean showInDetailsActivity) {
private void handleGpxImport(final Uri gpxFile, final String fileName, final boolean save, final boolean useImportDir, executeImportTask(new GpxImportTask(this, activity, gpxFile, fileName, save, useImportDir, showInDetailsActivity));
final boolean showInDetailsActivity) {
AsyncTask<Void, Void, GPXFile> gpxImportTask = new BaseImportAsyncTask<Void, Void, GPXFile>() {
@Override
protected GPXFile doInBackground(Void... nothing) {
InputStream is = null;
try {
is = app.getContentResolver().openInputStream(gpxFile);
if (is != null) {
return GPXUtilities.loadGPXFile(is);
}
} catch (FileNotFoundException e) {
//
} catch (SecurityException e) {
log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
}
return null;
} }
@Override private void handleGpxOrFavouritesImport(Uri fileUri, String fileName, boolean save, boolean useImportDir,
protected void onPostExecute(GPXFile result) { boolean forceImportFavourites, boolean forceImportGpx) {
hideProgress(); executeImportTask(new GpxOrFavouritesImportTask(this, activity, fileUri, fileName, save, useImportDir, forceImportFavourites, forceImportGpx));
handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity);
}
};
executeImportTask(gpxImportTask);
} }
@SuppressLint("StaticFieldLeak") private void importFavoritesImpl(GPXFile gpxFile, String fileName, boolean forceImportFavourites) {
private void handleGpxOrFavouritesImport(final Uri fileUri, final String fileName, final boolean save, executeImportTask(new FavoritesImportTask(activity, gpxFile, fileName, forceImportFavourites));
final boolean useImportDir, final boolean forceImportFavourites, }
final boolean forceImportGpx) {
AsyncTask<Void, Void, GPXFile> gpxOrFavouritesImportTask = new BaseImportAsyncTask<Void, Void, GPXFile>() {
@Override private void handleKmzImport(Uri kmzFile, String name, boolean save, boolean useImportDir) {
protected GPXFile doInBackground(Void... nothing) { executeImportTask(new KmzImportTask(this, activity, kmzFile, name, save, useImportDir));
InputStream is = null;
ZipInputStream zis = null;
try {
is = app.getContentResolver().openInputStream(fileUri);
if (is != null) {
if (fileName != null && fileName.endsWith(KML_SUFFIX)) {
final String result = Kml2Gpx.toGpx(is);
if (result != null) {
try {
return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
return null;
} }
private void handleKmlImport(Uri kmlFile, String name, boolean save, boolean useImportDir) {
executeImportTask(new KmlImportTask(this, activity, kmlFile, name, save, useImportDir));
} }
} else if (fileName != null && fileName.endsWith(KMZ_SUFFIX)) {
try { private void handleObfImport(Uri obfFile, String name) {
zis = new ZipInputStream(is); executeImportTask(new ObfImportTask(activity, obfFile, name));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.getName().endsWith(KML_SUFFIX)) {
final String result = Kml2Gpx.toGpx(zis);
if (result != null) {
try {
return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
return null;
} }
private void handleSqliteTileImport(Uri uri, String name) {
executeImportTask(new SqliteTileImportTask(activity, uri, name));
} }
}
} private void handleOsmAndSettingsImport(Uri intentUri, String fileName, Bundle extras, CallbackWithObject<List<SettingsItem>> callback) {
} catch (Exception e) { if (extras != null && extras.containsKey(SettingsHelper.SETTINGS_VERSION_KEY) && extras.containsKey(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY)) {
return null; int version = extras.getInt(SettingsHelper.SETTINGS_VERSION_KEY, -1);
} String latestChanges = extras.getString(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY);
handleOsmAndSettingsImport(intentUri, fileName, latestChanges, version, callback);
} else { } else {
return GPXUtilities.loadGPXFile(is); handleOsmAndSettingsImport(intentUri, fileName, null, -1, callback);
} }
} }
} catch (FileNotFoundException e) {
//
} catch (SecurityException e) {
log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
Algorithms.closeStream(zis);
}
return null;
}
@Override private void handleOsmAndSettingsImport(Uri uri, String name, String latestChanges, int version,
protected void onPostExecute(final GPXFile result) { CallbackWithObject<List<SettingsItem>> callback) {
hideProgress(); executeImportTask(new SettingsImportTask(activity, uri, name, latestChanges, version, callback));
importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx);
}
};
executeImportTask(gpxOrFavouritesImportTask);
} }
@SuppressLint("StaticFieldLeak") private void handleXmlFileImport(Uri intentUri, String fileName, CallbackWithObject routingCallback) {
private void importFavoritesImpl(final GPXFile gpxFile, final String fileName, final boolean forceImportFavourites) { executeImportTask(new XmlImportTask(activity, intentUri, fileName, routingCallback));
AsyncTask<Void, Void, GPXFile> favoritesImportTask = new BaseImportAsyncTask<Void, Void, GPXFile>() {
@Override
protected GPXFile doInBackground(Void... nothing) {
final List<FavouritePoint> favourites = asFavourites(gpxFile.getPoints(),
fileName, forceImportFavourites);
final FavouritesDbHelper favoritesHelper = app.getFavorites();
for (final FavouritePoint favourite : favourites) {
favoritesHelper.deleteFavourite(favourite, false);
favoritesHelper.addFavourite(favourite, false);
}
favoritesHelper.sortAll();
favoritesHelper.saveCurrentPointsIntoFile();
return null;
}
@Override
protected void onPostExecute(GPXFile result) {
hideProgress();
Toast.makeText(activity, R.string.fav_imported_sucessfully, Toast.LENGTH_LONG).show();
final Intent newIntent = new Intent(activity,
app.getAppCustomization().getFavoritesActivity());
newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
newIntent.putExtra(TAB_ID, FAV_TAB);
activity.startActivity(newIntent);
}
};
executeImportTask(favoritesImportTask);
}
@SuppressLint("StaticFieldLeak")
private void handleKmzImport(final Uri kmzFile, final String name, final boolean save, final boolean useImportDir) {
AsyncTask<Void, Void, GPXFile> kmzImportTask = new BaseImportAsyncTask<Void, Void, GPXFile>() {
@Override
protected GPXFile doInBackground(Void... voids) {
InputStream is = null;
ZipInputStream zis = null;
try {
is = app.getContentResolver().openInputStream(kmzFile);
if (is != null) {
zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.getName().endsWith(KML_SUFFIX)) {
final String result = Kml2Gpx.toGpx(zis);
if (result != null) {
try {
return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
Algorithms.closeStream(zis);
}
return null;
}
@Override
protected void onPostExecute(GPXFile result) {
hideProgress();
handleResult(result, name, save, useImportDir, false);
}
};
executeImportTask(kmzImportTask);
}
@SuppressLint("StaticFieldLeak")
private void handleKmlImport(final Uri kmlFile, final String name, final boolean save, final boolean useImportDir) {
AsyncTask<Void, Void, GPXFile> kmlImportTask = new BaseImportAsyncTask<Void, Void, GPXFile>() {
@Override
protected GPXFile doInBackground(Void... nothing) {
InputStream is = null;
try {
is = app.getContentResolver().openInputStream(kmlFile);
if (is != null) {
final String result = Kml2Gpx.toGpx(is);
if (result != null) {
try {
return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
} catch (FileNotFoundException e) {
//
} catch (SecurityException e) {
log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
}
return null;
}
@Override
protected void onPostExecute(GPXFile result) {
hideProgress();
handleResult(result, name, save, useImportDir, false);
}
};
executeImportTask(kmlImportTask);
}
@SuppressLint("StaticFieldLeak")
private void handleObfImport(final Uri obfFile, final String name) {
AsyncTask<Void, Void, String> obfImportTask = new BaseImportAsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
String error = copyFile(app, getObfDestFile(name), obfFile, false);
if (error == null) {
app.getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS, new ArrayList<String>());
app.getDownloadThread().updateLoadedFiles();
return app.getString(R.string.map_imported_successfully);
}
return app.getString(R.string.map_import_error) + ": " + error;
}
@Override
protected void onPostExecute(String message) {
hideProgress();
app.showShortToastMessage(message);
}
};
executeImportTask(obfImportTask);
}
@NonNull
private File getObfDestFile(@NonNull String name) {
if (name.endsWith(IndexConstants.BINARY_ROAD_MAP_INDEX_EXT)) {
return app.getAppPath(IndexConstants.ROADS_INDEX_DIR + name);
} else if (name.endsWith(IndexConstants.BINARY_WIKI_MAP_INDEX_EXT)) {
return app.getAppPath(IndexConstants.WIKI_INDEX_DIR + name);
}
return app.getAppPath(name);
} }
@Nullable @Nullable
@ -538,36 +317,6 @@ public class ImportHelper {
return error; return error;
} }
@SuppressLint("StaticFieldLeak")
private void handleSqliteTileImport(final Uri uri, final String name) {
AsyncTask<Void, Void, String> sqliteTileImportTask = new BaseImportAsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
return copyFile(app, app.getAppPath(IndexConstants.TILES_INDEX_DIR + name), uri, false);
}
@Override
protected void onPostExecute(String error) {
hideProgress();
if (error == null) {
OsmandRasterMapsPlugin plugin = OsmandPlugin.getPlugin(OsmandRasterMapsPlugin.class);
if (plugin != null && !plugin.isActive() && !plugin.needsInstallation()) {
OsmandPlugin.enablePlugin(getMapActivity(), app, plugin, true);
}
MapActivity mapActivity = getMapActivity();
if (mapActivity != null) {
mapActivity.getMapLayers().selectMapLayer(mapActivity.getMapView(), null, null);
}
Toast.makeText(app, app.getString(R.string.map_imported_successfully), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(app, app.getString(R.string.map_import_error) + ": " + error, Toast.LENGTH_SHORT).show();
}
}
};
executeImportTask(sqliteTileImportTask);
}
public void chooseFileToImport(final ImportType importType, final CallbackWithObject callback) { public void chooseFileToImport(final ImportType importType, final CallbackWithObject callback) {
final MapActivity mapActivity = getMapActivity(); final MapActivity mapActivity = getMapActivity();
if (mapActivity == null) { if (mapActivity == null) {
@ -627,254 +376,12 @@ public class ImportHelper {
return intent; return intent;
} }
private void handleOsmAndSettingsImport(Uri intentUri, String fileName, Bundle extras, CallbackWithObject<List<SettingsItem>> callback) { protected void handleResult(GPXFile result, String name, boolean save,
if (extras != null && extras.containsKey(SettingsHelper.SETTINGS_VERSION_KEY) && extras.containsKey(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY)) {
int version = extras.getInt(SettingsHelper.SETTINGS_VERSION_KEY, -1);
String latestChanges = extras.getString(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY);
handleOsmAndSettingsImport(intentUri, fileName, latestChanges, version, callback);
} else {
handleOsmAndSettingsImport(intentUri, fileName, null, -1, callback);
}
}
@SuppressLint("StaticFieldLeak")
private void handleOsmAndSettingsImport(final Uri uri, final String name, final String latestChanges, final int version,
final CallbackWithObject<List<SettingsItem>> callback) {
AsyncTask<Void, Void, String> settingsImportTask = new BaseImportAsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
File tempDir = app.getAppPath(IndexConstants.TEMP_DIR);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
File dest = new File(tempDir, name);
return copyFile(app, dest, uri, true);
}
@Override
protected void onPostExecute(String error) {
File tempDir = app.getAppPath(IndexConstants.TEMP_DIR);
final File file = new File(tempDir, name);
if (error == null && file.exists()) {
app.getSettingsHelper().collectSettings(file, latestChanges, version, new SettingsCollectListener() {
@Override
public void onSettingsCollectFinished(boolean succeed, boolean empty, @NonNull List<SettingsItem> items) {
hideProgress();
if (succeed) {
List<SettingsItem> pluginIndependentItems = new ArrayList<>();
List<PluginSettingsItem> pluginSettingsItems = new ArrayList<>();
for (SettingsItem item : items) {
if (item instanceof PluginSettingsItem) {
pluginSettingsItems.add((PluginSettingsItem) item);
} else if (Algorithms.isEmpty(item.getPluginId())) {
pluginIndependentItems.add(item);
}
}
for (PluginSettingsItem pluginItem : pluginSettingsItems) {
handlePluginImport(pluginItem, file);
}
if (!pluginIndependentItems.isEmpty()) {
FragmentManager fragmentManager = activity.getSupportFragmentManager();
ImportSettingsFragment.showInstance(fragmentManager, pluginIndependentItems, file);
}
} else if (empty) {
app.showShortToastMessage(app.getString(R.string.file_import_error, name, app.getString(R.string.shared_string_unexpected_error)));
}
}
});
} else {
hideProgress();
app.showShortToastMessage(app.getString(R.string.file_import_error, name, error));
}
}
};
executeImportTask(settingsImportTask);
}
private void handlePluginImport(final PluginSettingsItem pluginItem, final File file) {
final ProgressDialog progress = new ProgressDialog(activity);
progress.setTitle(app.getString(R.string.loading_smth, ""));
progress.setMessage(app.getString(R.string.importing_from, pluginItem.getPublicName(app)));
progress.setIndeterminate(true);
progress.setCancelable(false);
if (AndroidUtils.isActivityNotDestroyed(activity)) {
progress.show();
}
final SettingsImportListener importListener = new SettingsImportListener() {
@Override
public void onSettingsImportFinished(boolean succeed, @NonNull List<SettingsItem> items) {
if (AndroidUtils.isActivityNotDestroyed(activity)) {
progress.dismiss();
}
CustomOsmandPlugin plugin = pluginItem.getPlugin();
plugin.loadResources();
for (SettingsItem item : items) {
if (item instanceof ProfileSettingsItem) {
((ProfileSettingsItem) item).applyAdditionalPrefs();
}
}
if (!Algorithms.isEmpty(plugin.getDownloadMaps())) {
app.getDownloadThread().runReloadIndexFilesSilent();
}
if (!Algorithms.isEmpty(plugin.getRendererNames())) {
app.getRendererRegistry().updateExternalRenderers();
}
if (!Algorithms.isEmpty(plugin.getRouterNames())) {
loadRoutingFiles(app, null);
}
if (activity != null) {
plugin.onInstall(app, activity);
}
String pluginId = pluginItem.getPluginId();
File pluginDir = new File(app.getAppPath(null), IndexConstants.PLUGINS_DIR + pluginId);
app.getSettingsHelper().exportSettings(pluginDir, "items", null, items, false);
}
};
List<SettingsItem> pluginItems = new ArrayList<>(pluginItem.getPluginDependentItems());
pluginItems.add(0, pluginItem);
app.getSettingsHelper().checkDuplicates(file, pluginItems, pluginItems, new CheckDuplicatesListener() {
@Override
public void onDuplicatesChecked(@NonNull List<Object> duplicates, List<SettingsItem> items) {
for (SettingsItem item : items) {
item.setShouldReplace(true);
}
app.getSettingsHelper().importSettings(file, items, "", 1, importListener);
}
});
}
@SuppressLint("StaticFieldLeak")
private void handleXmlFileImport(final Uri intentUri, final String fileName,
final CallbackWithObject routingCallback) {
AsyncTask<Void, Void, String> renderingImportTask = new BaseImportAsyncTask<Void, Void, String>() {
private String destFileName;
private ImportType importType;
@Override
protected void onPreExecute() {
showProgress();
destFileName = fileName;
}
@Override
protected String doInBackground(Void... voids) {
checkImportType();
if (importType != null) {
File dest = getDestinationFile();
if (dest != null) {
return copyFile(app, dest, intentUri, true);
}
}
return app.getString(R.string.file_import_error, destFileName, app.getString(R.string.unsupported_type_error));
}
@Override
protected void onPostExecute(String error) {
File destDir = getDestinationDir();
File file = new File(destDir, destFileName);
if (error == null && file.exists()) {
if (importType == ImportType.RENDERING) {
app.getRendererRegistry().updateExternalRenderers();
app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName));
hideProgress();
} else if (importType == ImportType.ROUTING) {
loadRoutingFiles(app, new AppInitializer.LoadRoutingFilesCallback() {
@Override
public void onRoutingFilesLoaded() {
hideProgress();
RoutingConfiguration.Builder builder = app.getCustomRoutingConfig(destFileName);
if (builder != null) {
if (routingCallback != null) {
routingCallback.processResult(builder);
}
app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName));
} else {
app.showToastMessage(app.getString(R.string.file_does_not_contain_routing_rules, destFileName));
}
}
});
}
} else {
hideProgress();
app.showShortToastMessage(app.getString(R.string.file_import_error, destFileName, error));
}
}
private File getDestinationDir() {
if (importType == ImportType.ROUTING) {
return app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR);
} else if (importType == ImportType.RENDERING) {
return app.getAppPath(IndexConstants.RENDERERS_DIR);
}
return null;
}
private File getDestinationFile() {
File destDir = getDestinationDir();
if (destDir != null) {
if (!destDir.exists()) {
destDir.mkdirs();
}
if (importType == ImportType.RENDERING && !destFileName.endsWith(RENDERER_INDEX_EXT)) {
String fileName = Algorithms.getFileNameWithoutExtension(destFileName);
destFileName = fileName + RENDERER_INDEX_EXT;
}
File destFile = new File(destDir, destFileName);
while (destFile.exists()) {
destFileName = AndroidUtils.createNewFileName(destFileName);
destFile = new File(destDir, destFileName);
}
return destFile;
}
return null;
}
private void checkImportType() {
InputStream is = null;
try {
is = app.getContentResolver().openInputStream(intentUri);
if (is != null) {
XmlPullParser parser = PlatformUtil.newXMLPullParser();
parser.setInput(is, "UTF-8");
int tok;
while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {
if (tok == XmlPullParser.START_TAG) {
String name = parser.getName();
if ("osmand_routing_config".equals(name)) {
importType = ImportType.ROUTING;
} else if ("renderingStyle".equals(name)) {
importType = ImportType.RENDERING;
}
break;
}
}
Algorithms.closeStream(is);
}
} catch (FileNotFoundException | XmlPullParserException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} catch (SecurityException e) {
log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
}
}
};
executeImportTask(renderingImportTask);
}
private void handleResult(GPXFile result, String name, boolean save,
boolean useImportDir, boolean forceImportFavourites) { boolean useImportDir, boolean forceImportFavourites) {
handleResult(result, name, save, useImportDir, forceImportFavourites, true); handleResult(result, name, save, useImportDir, forceImportFavourites, true);
} }
private void handleResult(final GPXFile result, final String name, final boolean save, protected void handleResult(final GPXFile result, final String name, final boolean save,
final boolean useImportDir, boolean forceImportFavourites, boolean showInDetailsActivity) { final boolean useImportDir, boolean forceImportFavourites, boolean showInDetailsActivity) {
if (result != null) { if (result != null) {
if (result.error != null) { if (result.error != null) {
@ -937,7 +444,7 @@ public class ImportHelper {
if (useImportDir) { if (useImportDir) {
importDir = app.getAppPath(IndexConstants.GPX_IMPORT_DIR); importDir = app.getAppPath(IndexConstants.GPX_IMPORT_DIR);
} else { } else {
importDir = app.getAppPath(IndexConstants.GPX_INDEX_DIR); importDir = app.getAppPath(GPX_INDEX_DIR);
} }
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
importDir.mkdirs(); importDir.mkdirs();
@ -1058,7 +565,7 @@ public class ImportHelper {
} }
} }
private void importGpxOrFavourites(final GPXFile gpxFile, final String fileName, final boolean save, protected void importGpxOrFavourites(final GPXFile gpxFile, final String fileName, final boolean save,
final boolean useImportDir, final boolean forceImportFavourites, final boolean useImportDir, final boolean forceImportFavourites,
final boolean forceImportGpx) { final boolean forceImportGpx) {
if (gpxFile == null || gpxFile.isPointsEmpty()) { if (gpxFile == null || gpxFile.isPointsEmpty()) {
@ -1083,11 +590,10 @@ public class ImportHelper {
.setPositiveButton(R.string.shared_string_import, importAsTrackListener) .setPositiveButton(R.string.shared_string_import, importAsTrackListener)
.setNegativeButton(R.string.shared_string_cancel, importAsTrackListener) .setNegativeButton(R.string.shared_string_cancel, importAsTrackListener)
.show(); .show();
return;
} else { } else {
handleResult(gpxFile, fileName, save, useImportDir, false); handleResult(gpxFile, fileName, save, useImportDir, false);
return;
} }
return;
} }
if (forceImportFavourites) { if (forceImportFavourites) {
@ -1110,7 +616,7 @@ public class ImportHelper {
} }
} }
private List<FavouritePoint> asFavourites(final List<WptPt> wptPts, String fileName, boolean forceImportFavourites) { protected static List<FavouritePoint> asFavourites(OsmandApplication app, List<WptPt> wptPts, String fileName, boolean forceImportFavourites) {
final List<FavouritePoint> favourites = new ArrayList<>(); final List<FavouritePoint> favourites = new ArrayList<>();
for (WptPt p : wptPts) { for (WptPt p : wptPts) {
if (p.name != null) { if (p.name != null) {
@ -1155,27 +661,4 @@ public class ImportHelper {
importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requests); importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requests);
} }
} }
protected abstract class BaseImportAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
protected ProgressDialog progress;
@Override
protected void onPreExecute() {
showProgress();
}
protected void showProgress() {
if (AndroidUtils.isActivityNotDestroyed(activity)) {
String title = app.getString(R.string.loading_smth, "");
progress = ProgressDialog.show(activity, title, app.getString(R.string.loading_data));
}
}
protected void hideProgress() {
if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) {
progress.dismiss();
}
}
}
} }

View file

@ -0,0 +1,71 @@
package net.osmand.plus.importfiles;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.GPXUtilities;
import net.osmand.GPXUtilities.GPXFile;
import net.osmand.plus.helpers.Kml2Gpx;
import net.osmand.util.Algorithms;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
class KmlImportTask extends BaseImportAsyncTask<Void, Void, GPXUtilities.GPXFile> {
private ImportHelper importHelper;
private Uri uri;
private String name;
private boolean save;
private boolean useImportDir;
public KmlImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity,
@NonNull Uri uri, String name, boolean save, boolean useImportDir) {
super(activity);
this.importHelper = importHelper;
this.uri = uri;
this.name = name;
this.save = save;
this.useImportDir = useImportDir;
}
@Override
protected GPXFile doInBackground(Void... nothing) {
InputStream is = null;
try {
is = app.getContentResolver().openInputStream(uri);
if (is != null) {
return loadGpxFromKml(is);
}
} catch (FileNotFoundException e) {
//
} catch (SecurityException e) {
ImportHelper.log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
}
return null;
}
@Override
protected void onPostExecute(GPXFile result) {
hideProgress();
importHelper.handleResult(result, name, save, useImportDir, false);
}
protected static GPXFile loadGpxFromKml(@NonNull InputStream is) {
String result = Kml2Gpx.toGpx(is);
if (result != null) {
try {
return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
return null;
}
}
return null;
}
}

View file

@ -0,0 +1,67 @@
package net.osmand.plus.importfiles;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.GPXUtilities;
import net.osmand.GPXUtilities.GPXFile;
import net.osmand.util.Algorithms;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import static net.osmand.plus.importfiles.ImportHelper.KML_SUFFIX;
import static net.osmand.plus.importfiles.KmlImportTask.loadGpxFromKml;
class KmzImportTask extends BaseImportAsyncTask<Void, Void, GPXUtilities.GPXFile> {
private ImportHelper importHelper;
private Uri uri;
private String name;
private boolean save;
private boolean useImportDir;
public KmzImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity,
@NonNull Uri uri, @NonNull String name, boolean save, boolean useImportDir) {
super(activity);
this.importHelper = importHelper;
this.uri = uri;
this.name = name;
this.save = save;
this.useImportDir = useImportDir;
}
@Override
protected GPXFile doInBackground(Void... voids) {
InputStream is = null;
ZipInputStream zis = null;
try {
is = app.getContentResolver().openInputStream(uri);
if (is != null) {
zis = new ZipInputStream(is);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.getName().endsWith(KML_SUFFIX)) {
return loadGpxFromKml(is);
}
}
}
} catch (Exception e) {
ImportHelper.log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
Algorithms.closeStream(zis);
}
return null;
}
@Override
protected void onPostExecute(GPXUtilities.GPXFile result) {
hideProgress();
importHelper.handleResult(result, name, save, useImportDir, false);
}
}

View file

@ -0,0 +1,52 @@
package net.osmand.plus.importfiles;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.IProgress;
import net.osmand.IndexConstants;
import net.osmand.plus.R;
import java.io.File;
import java.util.ArrayList;
class ObfImportTask extends BaseImportAsyncTask<Void, Void, String> {
private Uri uri;
private String name;
public ObfImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, String name) {
super(activity);
this.uri = uri;
this.name = name;
}
@Override
protected String doInBackground(Void... voids) {
String error = ImportHelper.copyFile(app, getObfDestFile(name), uri, false);
if (error == null) {
app.getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS, new ArrayList<String>());
app.getDownloadThread().updateLoadedFiles();
return app.getString(R.string.map_imported_successfully);
}
return app.getString(R.string.map_import_error) + ": " + error;
}
@Override
protected void onPostExecute(String message) {
hideProgress();
app.showShortToastMessage(message);
}
@NonNull
private File getObfDestFile(@NonNull String name) {
if (name.endsWith(IndexConstants.BINARY_ROAD_MAP_INDEX_EXT)) {
return app.getAppPath(IndexConstants.ROADS_INDEX_DIR + name);
} else if (name.endsWith(IndexConstants.BINARY_WIKI_MAP_INDEX_EXT)) {
return app.getAppPath(IndexConstants.WIKI_INDEX_DIR + name);
}
return app.getAppPath(name);
}
}

View file

@ -0,0 +1,158 @@
package net.osmand.plus.importfiles;
import android.app.ProgressDialog;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import net.osmand.AndroidUtils;
import net.osmand.CallbackWithObject;
import net.osmand.IndexConstants;
import net.osmand.plus.CustomOsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.settings.backend.SettingsHelper.CheckDuplicatesListener;
import net.osmand.plus.settings.backend.SettingsHelper.PluginSettingsItem;
import net.osmand.plus.settings.backend.SettingsHelper.ProfileSettingsItem;
import net.osmand.plus.settings.backend.SettingsHelper.SettingsCollectListener;
import net.osmand.plus.settings.backend.SettingsHelper.SettingsImportListener;
import net.osmand.plus.settings.backend.SettingsHelper.SettingsItem;
import net.osmand.plus.settings.fragments.ImportSettingsFragment;
import net.osmand.util.Algorithms;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static net.osmand.IndexConstants.TEMP_DIR;
import static net.osmand.plus.AppInitializer.loadRoutingFiles;
class SettingsImportTask extends BaseImportAsyncTask<Void, Void, String> {
private Uri uri;
private String name;
private String latestChanges;
private int version;
private CallbackWithObject<List<SettingsItem>> callback;
public SettingsImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri,
@NonNull String name, String latestChanges, int version,
CallbackWithObject<List<SettingsItem>> callback) {
super(activity);
this.uri = uri;
this.name = name;
this.latestChanges = latestChanges;
this.version = version;
this.callback = callback;
}
@Override
protected String doInBackground(Void... voids) {
File tempDir = app.getAppPath(TEMP_DIR);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
File dest = new File(tempDir, name);
return ImportHelper.copyFile(app, dest, uri, true);
}
@Override
protected void onPostExecute(String error) {
File tempDir = app.getAppPath(TEMP_DIR);
final File file = new File(tempDir, name);
if (error == null && file.exists()) {
app.getSettingsHelper().collectSettings(file, latestChanges, version, new SettingsCollectListener() {
@Override
public void onSettingsCollectFinished(boolean succeed, boolean empty, @NonNull List<SettingsItem> items) {
hideProgress();
if (succeed) {
List<SettingsItem> pluginIndependentItems = new ArrayList<>();
List<PluginSettingsItem> pluginSettingsItems = new ArrayList<>();
for (SettingsItem item : items) {
if (item instanceof PluginSettingsItem) {
pluginSettingsItems.add((PluginSettingsItem) item);
} else if (Algorithms.isEmpty(item.getPluginId())) {
pluginIndependentItems.add(item);
}
}
for (PluginSettingsItem pluginItem : pluginSettingsItems) {
handlePluginImport(pluginItem, file);
}
if (!pluginIndependentItems.isEmpty()) {
FragmentActivity activity = activityRef.get();
if (activity != null) {
FragmentManager fragmentManager = activity.getSupportFragmentManager();
ImportSettingsFragment.showInstance(fragmentManager, pluginIndependentItems, file);
}
}
} else if (empty) {
app.showShortToastMessage(app.getString(R.string.file_import_error, name, app.getString(R.string.shared_string_unexpected_error)));
}
}
});
} else {
hideProgress();
app.showShortToastMessage(app.getString(R.string.file_import_error, name, error));
}
}
private void handlePluginImport(final PluginSettingsItem pluginItem, final File file) {
FragmentActivity activity = activityRef.get();
final ProgressDialog progress;
if (AndroidUtils.isActivityNotDestroyed(activity)) {
progress = new ProgressDialog(activity);
progress.setTitle(app.getString(R.string.loading_smth, ""));
progress.setMessage(app.getString(R.string.importing_from, pluginItem.getPublicName(app)));
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
} else {
progress = null;
}
final SettingsImportListener importListener = new SettingsImportListener() {
@Override
public void onSettingsImportFinished(boolean succeed, @NonNull List<SettingsItem> items) {
FragmentActivity activity = activityRef.get();
if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) {
progress.dismiss();
}
CustomOsmandPlugin plugin = pluginItem.getPlugin();
plugin.loadResources();
for (SettingsItem item : items) {
if (item instanceof ProfileSettingsItem) {
((ProfileSettingsItem) item).applyAdditionalPrefs();
}
}
if (!Algorithms.isEmpty(plugin.getDownloadMaps())) {
app.getDownloadThread().runReloadIndexFilesSilent();
}
if (!Algorithms.isEmpty(plugin.getRendererNames())) {
app.getRendererRegistry().updateExternalRenderers();
}
if (!Algorithms.isEmpty(plugin.getRouterNames())) {
loadRoutingFiles(app, null);
}
if (activity != null) {
plugin.onInstall(app, activity);
}
String pluginId = pluginItem.getPluginId();
File pluginDir = new File(app.getAppPath(null), IndexConstants.PLUGINS_DIR + pluginId);
app.getSettingsHelper().exportSettings(pluginDir, "items", null, items, false);
}
};
List<SettingsItem> pluginItems = new ArrayList<>(pluginItem.getPluginDependentItems());
pluginItems.add(0, pluginItem);
app.getSettingsHelper().checkDuplicates(file, pluginItems, pluginItems, new CheckDuplicatesListener() {
@Override
public void onDuplicatesChecked(@NonNull List<Object> duplicates, List<SettingsItem> items) {
for (SettingsItem item : items) {
item.setShouldReplace(true);
}
app.getSettingsHelper().importSettings(file, items, "", 1, importListener);
}
});
}
}

View file

@ -0,0 +1,50 @@
package net.osmand.plus.importfiles;
import android.net.Uri;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import net.osmand.plus.OsmandPlugin;
import net.osmand.plus.R;
import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin;
import static net.osmand.IndexConstants.TILES_INDEX_DIR;
class SqliteTileImportTask extends BaseImportAsyncTask<Void, Void, String> {
private Uri uri;
private String name;
public SqliteTileImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, @NonNull String name) {
super(activity);
this.uri = uri;
this.name = name;
}
@Override
protected String doInBackground(Void... voids) {
return ImportHelper.copyFile(app, app.getAppPath(TILES_INDEX_DIR + name), uri, false);
}
@Override
protected void onPostExecute(String error) {
hideProgress();
if (error == null) {
FragmentActivity activity = activityRef.get();
OsmandRasterMapsPlugin plugin = OsmandPlugin.getPlugin(OsmandRasterMapsPlugin.class);
if (plugin != null && !plugin.isActive() && !plugin.needsInstallation()) {
OsmandPlugin.enablePlugin(activity, app, plugin, true);
}
if (activity instanceof MapActivity) {
MapActivity mapActivity = (MapActivity) activity;
mapActivity.getMapLayers().selectMapLayer(mapActivity.getMapView(), null, null);
}
Toast.makeText(app, app.getString(R.string.map_imported_successfully), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(app, app.getString(R.string.map_import_error) + ": " + error, Toast.LENGTH_SHORT).show();
}
}
}

View file

@ -0,0 +1,149 @@
package net.osmand.plus.importfiles;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import net.osmand.AndroidUtils;
import net.osmand.CallbackWithObject;
import net.osmand.IndexConstants;
import net.osmand.PlatformUtil;
import net.osmand.plus.AppInitializer.LoadRoutingFilesCallback;
import net.osmand.plus.R;
import net.osmand.plus.importfiles.ImportHelper.ImportType;
import net.osmand.router.RoutingConfiguration.Builder;
import net.osmand.util.Algorithms;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import static net.osmand.IndexConstants.RENDERER_INDEX_EXT;
import static net.osmand.plus.AppInitializer.loadRoutingFiles;
class XmlImportTask extends BaseImportAsyncTask<Void, Void, String> {
private Uri intentUri;
private String destFileName;
private ImportType importType;
private CallbackWithObject routingCallback;
public XmlImportTask(@NonNull FragmentActivity activity, @NonNull Uri intentUri,
@NonNull String fileName, @Nullable CallbackWithObject routingCallback) {
super(activity);
this.intentUri = intentUri;
this.destFileName = fileName;
this.routingCallback = routingCallback;
}
@Override
protected String doInBackground(Void... voids) {
checkImportType();
if (importType != null) {
File dest = getDestinationFile();
if (dest != null) {
return ImportHelper.copyFile(app, dest, intentUri, true);
}
}
return app.getString(R.string.file_import_error, destFileName, app.getString(R.string.unsupported_type_error));
}
@Override
protected void onPostExecute(String error) {
File destDir = getDestinationDir();
File file = new File(destDir, destFileName);
if (error == null && file.exists()) {
if (importType == ImportType.RENDERING) {
app.getRendererRegistry().updateExternalRenderers();
app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName));
hideProgress();
} else if (importType == ImportType.ROUTING) {
loadRoutingFiles(app, new LoadRoutingFilesCallback() {
@Override
public void onRoutingFilesLoaded() {
hideProgress();
Builder builder = app.getCustomRoutingConfig(destFileName);
if (builder != null) {
if (routingCallback != null) {
routingCallback.processResult(builder);
}
app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName));
} else {
app.showToastMessage(app.getString(R.string.file_does_not_contain_routing_rules, destFileName));
}
}
});
}
} else {
hideProgress();
app.showShortToastMessage(app.getString(R.string.file_import_error, destFileName, error));
}
}
private File getDestinationDir() {
if (importType == ImportType.ROUTING) {
return app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR);
} else if (importType == ImportType.RENDERING) {
return app.getAppPath(IndexConstants.RENDERERS_DIR);
}
return null;
}
private File getDestinationFile() {
File destDir = getDestinationDir();
if (destDir != null) {
if (!destDir.exists()) {
destDir.mkdirs();
}
if (importType == ImportType.RENDERING && !destFileName.endsWith(RENDERER_INDEX_EXT)) {
String fileName = Algorithms.getFileNameWithoutExtension(destFileName);
destFileName = fileName + RENDERER_INDEX_EXT;
}
File destFile = new File(destDir, destFileName);
while (destFile.exists()) {
destFileName = AndroidUtils.createNewFileName(destFileName);
destFile = new File(destDir, destFileName);
}
return destFile;
}
return null;
}
private void checkImportType() {
InputStream is = null;
try {
is = app.getContentResolver().openInputStream(intentUri);
if (is != null) {
XmlPullParser parser = PlatformUtil.newXMLPullParser();
parser.setInput(is, "UTF-8");
int tok;
while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {
if (tok == XmlPullParser.START_TAG) {
String name = parser.getName();
if ("osmand_routing_config".equals(name)) {
importType = ImportType.ROUTING;
} else if ("renderingStyle".equals(name)) {
importType = ImportType.RENDERING;
}
break;
}
}
Algorithms.closeStream(is);
}
} catch (FileNotFoundException | XmlPullParserException e) {
ImportHelper.log.error(e);
} catch (IOException e) {
ImportHelper.log.error(e);
} catch (SecurityException e) {
ImportHelper.log.error(e.getMessage(), e);
} finally {
Algorithms.closeStream(is);
}
}
}

View file

@ -28,8 +28,8 @@ import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerItem;
import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem;
import net.osmand.plus.helpers.GpxTrackAdapter; import net.osmand.plus.helpers.GpxTrackAdapter;
import net.osmand.plus.helpers.GpxUiHelper.GPXInfo; import net.osmand.plus.helpers.GpxUiHelper.GPXInfo;
import net.osmand.plus.helpers.ImportHelper; import net.osmand.plus.importfiles.ImportHelper;
import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;

View file

@ -30,8 +30,8 @@ import net.osmand.plus.R;
import net.osmand.plus.activities.FavoritesTreeFragment; import net.osmand.plus.activities.FavoritesTreeFragment;
import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.MapActivity;
import net.osmand.plus.activities.TabActivity; import net.osmand.plus.activities.TabActivity;
import net.osmand.plus.helpers.ImportHelper; import net.osmand.plus.importfiles.ImportHelper;
import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener;
import net.osmand.plus.settings.backend.OsmAndAppCustomization; import net.osmand.plus.settings.backend.OsmAndAppCustomization;
import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.settings.backend.OsmandSettings;
import net.osmand.plus.views.controls.PagerSlidingTabStrip; import net.osmand.plus.views.controls.PagerSlidingTabStrip;

View file

@ -40,7 +40,7 @@ import org.apache.commons.logging.Log;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static net.osmand.plus.helpers.ImportHelper.ImportType.ROUTING; import static net.osmand.plus.importfiles.ImportHelper.ImportType.ROUTING;
public class SelectProfileBottomSheetDialogFragment extends BasePreferenceBottomSheet { public class SelectProfileBottomSheetDialogFragment extends BasePreferenceBottomSheet {

View file

@ -40,8 +40,8 @@ import net.osmand.plus.base.ContextMenuScrollFragment;
import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.AndroidUiHelper;
import net.osmand.plus.helpers.GpxUiHelper; import net.osmand.plus.helpers.GpxUiHelper;
import net.osmand.plus.helpers.GpxUiHelper.GPXInfo; import net.osmand.plus.helpers.GpxUiHelper.GPXInfo;
import net.osmand.plus.helpers.ImportHelper; import net.osmand.plus.importfiles.ImportHelper;
import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener;
import net.osmand.plus.measurementtool.GpxData; import net.osmand.plus.measurementtool.GpxData;
import net.osmand.plus.measurementtool.GpxData.ActionType; import net.osmand.plus.measurementtool.GpxData.ActionType;
import net.osmand.plus.measurementtool.MeasurementEditingContext; import net.osmand.plus.measurementtool.MeasurementEditingContext;

View file

@ -31,7 +31,7 @@ import net.osmand.plus.activities.PluginsActivity;
import net.osmand.plus.activities.SettingsActivity; import net.osmand.plus.activities.SettingsActivity;
import net.osmand.plus.activities.TrackActivity; import net.osmand.plus.activities.TrackActivity;
import net.osmand.plus.download.DownloadActivity; import net.osmand.plus.download.DownloadActivity;
import net.osmand.plus.helpers.ImportHelper; import net.osmand.plus.importfiles.ImportHelper;
import net.osmand.plus.helpers.WaypointHelper; import net.osmand.plus.helpers.WaypointHelper;
import net.osmand.plus.myplaces.FavoritesActivity; import net.osmand.plus.myplaces.FavoritesActivity;
import net.osmand.plus.routing.RouteCalculationResult; import net.osmand.plus.routing.RouteCalculationResult;

View file

@ -31,7 +31,7 @@ import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static net.osmand.plus.helpers.ImportHelper.ImportType.SETTINGS; import static net.osmand.plus.importfiles.ImportHelper.ImportType.SETTINGS;
import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.DIALOG_TYPE; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.DIALOG_TYPE;
import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.IS_PROFILE_IMPORTED_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.IS_PROFILE_IMPORTED_ARG;
import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.PROFILE_KEY_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.PROFILE_KEY_ARG;