Refactor index list and introduce road maps downloads

This commit is contained in:
Victor Shcherb 2012-11-15 10:28:38 +01:00
parent 36071ab902
commit 89eb3b8f09
15 changed files with 958 additions and 806 deletions

View file

@ -6,7 +6,6 @@
android:orientation="vertical" >
<!-- TextView android:id="@+id/Label" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="@string/select_index_file_to_download"></TextView -->
<EditText
android:id="@+id/search_box"
android:layout_width="fill_parent"

View file

@ -11,6 +11,11 @@
-->
<string name="rendering_attr_showRoadMaps_description">Select when to display roads-only maps:</string>
<string name="rendering_attr_showRoadMaps_name">Roads-only maps</string>
<string name="download_roads_only_item">Roads </string>
<string name="download_regular_maps">Regular maps</string>
<string name="download_roads_only_maps">Roads only maps</string>
<string name="rendering_attr_showRoadMaps_description">Select how to display roads-only maps:</string>
<string name="rendering_attr_showRoadMaps_name">Show roads-only maps</string>
<string name="safe_mode_description">Run the application in safe mode (using slower Android instead of native code).</string>
<string name="safe_mode">Safe mode</string>
<string name="native_library_not_running">The application is running in safe mode (disable it in the Settings).</string>

View file

@ -1378,7 +1378,7 @@ public class OsmandSettings {
new BooleanPreference("show_ruler", true).makeProfile().cache();
public final OsmandPreference<Integer> NUMBER_OF_FREE_DOWNLOADS = new IntPreference("free_downloads", 0).makeGlobal();
public final OsmandPreference<Integer> NUMBER_OF_FREE_DOWNLOADS = new IntPreference("free_downloads_v1", 0).makeGlobal();
public boolean checkFreeDownloadsNumberZero(){
if(!globalPreferences.contains(NUMBER_OF_FREE_DOWNLOADS.getId())){

View file

@ -11,19 +11,10 @@ import static net.osmand.data.IndexConstants.VOICE_VERSION;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
@ -34,49 +25,40 @@ import net.osmand.LogUtil;
import net.osmand.Version;
import net.osmand.access.AccessibleToast;
import net.osmand.data.IndexConstants;
import net.osmand.plus.DownloadOsmandIndexesHelper;
import net.osmand.plus.DownloadOsmandIndexesHelper.IndexItem;
import net.osmand.plus.IndexFileList;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.OsmandSettings.OsmandPreference;
import net.osmand.plus.ProgressDialogImplementation;
import net.osmand.plus.R;
import net.osmand.plus.ResourceManager;
import net.osmand.plus.activities.DownloadFileHelper.DownloadFileShowWarning;
import net.osmand.plus.download.DownloadEntry;
import net.osmand.plus.download.DownloadFileHelper;
import net.osmand.plus.download.DownloadFileHelper.DownloadFileShowWarning;
import net.osmand.plus.download.DownloadIndexAdapter;
import net.osmand.plus.download.DownloadIndexListThread;
import net.osmand.plus.download.DownloadOsmandIndexesHelper.IndexItem;
import net.osmand.plus.download.DownloadTracker;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StatFs;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
public class DownloadIndexActivity extends OsmandExpandableListActivity {
@ -88,22 +70,23 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
private static final int SELECT_ALL_ID = 1;
private static final int DESELECT_ALL_ID = 2;
private static final int FILTER_EXISTING_REGIONS = 3;
private static final int DOWNLOAD_FILES_TYPE = 4;
/** dialogs **/
protected static final int DIALOG_MAP_VERSION_UPDATE = 0;
protected static final int DIALOG_PROGRESS_FILE = 1;
protected static final int DIALOG_PROGRESS_LIST = 2;
public static final int DIALOG_MAP_VERSION_UPDATE = 0;
public static final int DIALOG_PROGRESS_FILE = 1;
public static final int DIALOG_PROGRESS_LIST = 2;
public static final String FILTER_KEY = "filter";
private static DownloadIndexListThread downloadListIndexThread;
private ProgressDialog progressFileDlg = null;
private Map<String, String> indexFileNames = null;
private Map<String, String> indexActivatedFileNames = null;
private TreeMap<String, DownloadEntry> entriesToDownload = new TreeMap<String, DownloadEntry>();
private DownloadActivityType type = DownloadActivityType.NORMAL_FILE;
private int MAXIMUM_AVAILABLE_FREE_DOWNLOADS = 16;
private int MAXIMUM_AVAILABLE_FREE_DOWNLOADS = 10;
private TextWatcher textWatcher ;
@ -111,6 +94,14 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
private DownloadFileHelper downloadFileHelper = null;
private OsmandSettings settings;
public enum DownloadActivityType {
NORMAL_FILE,
ROADS_FILE,
SRTM_FILE
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -135,8 +126,6 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
});
updateLoadedFiles();
filterText = (EditText) findViewById(R.id.search_box);
textWatcher = new TextWatcher() {
@Override
@ -165,9 +154,9 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
filterText.setText(filter);
}
}
if (downloadListIndexThread.getCachedIndexFiles() != null && downloadListIndexThread.isDownloadedFromInternet()) {
setListAdapter(new DownloadIndexAdapter(downloadListIndexThread.getCachedIndexFiles()));
DownloadIndexAdapter adapter = new DownloadIndexAdapter(this, downloadListIndexThread.getCachedIndexFiles());
setListAdapter(adapter);
} else {
downloadIndexList();
}
@ -180,10 +169,10 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
private void updateLoadedFiles() {
indexActivatedFileNames = getMyApplication().getResourceManager().getIndexFileNames();
indexFileNames = getMyApplication().getResourceManager().getIndexFileNames();
getMyApplication().getResourceManager().getBackupIndexes(indexFileNames);
public void updateLoadedFiles() {
if(getExpandableListAdapter() != null) {
((DownloadIndexAdapter)getExpandableListAdapter()).updateLoadedFiles();
}
}
private void downloadIndexList() {
@ -191,7 +180,6 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.clear();
@ -201,9 +189,19 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
menu.add(0, SELECT_ALL_ID, 0, R.string.select_all);
menu.add(0, DESELECT_ALL_ID, 0, R.string.deselect_all);
menu.add(0, FILTER_EXISTING_REGIONS, 0, R.string.filter_existing_indexes);
menu.add(0, DOWNLOAD_FILES_TYPE, 0, getType() == DownloadActivityType.NORMAL_FILE ?
R.string.download_roads_only_maps : R.string.download_regular_maps );
}
return true;
}
public DownloadActivityType getType() {
return type;
}
public TreeMap<String, DownloadEntry> getEntriesToDownload() {
return entriesToDownload;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
@ -215,11 +213,13 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
final DownloadIndexAdapter listAdapter = (DownloadIndexAdapter)getExpandableListAdapter();
if(item.getItemId() == SELECT_ALL_ID){
int selected = 0;
for (int i = 0; i < listAdapter.getChildrenCount(0); i++) {
IndexItem es = listAdapter.getChild(0, i);
if(!entriesToDownload.containsKey(es.getFileName())){
selected++;
entriesToDownload.put(es.getFileName(), es.createDownloadEntry(DownloadIndexActivity.this));
for (int j = 0; j < listAdapter.getGroupCount(); j++) {
for (int i = 0; i < listAdapter.getChildrenCount(j); i++) {
IndexItem es = listAdapter.getChild(j, i);
if (!entriesToDownload.containsKey(es.getFileName())) {
selected++;
entriesToDownload.put(es.getFileName(), es.createDownloadEntry(DownloadIndexActivity.this, type));
}
}
}
AccessibleToast.makeText(this, MessageFormat.format(getString(R.string.items_were_selected), selected), Toast.LENGTH_SHORT).show();
@ -228,15 +228,21 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
findViewById(R.id.DownloadButton).setVisibility(View.VISIBLE);
}
} else if (item.getItemId() == FILTER_EXISTING_REGIONS) {
final Collection<String> listAlreadyDownloaded = listAlreadyDownloadedWithAlternatives();
final Set<String> listAlreadyDownloaded = listAlreadyDownloadedWithAlternatives();
final List<IndexItem> filtered = new ArrayList<IndexItem>();
for (String file : listAlreadyDownloaded) {
IndexItem fileItem = listAdapter.getIndexFiles().get(file);
if (fileItem != null) {
for (IndexItem fileItem : listAdapter.getIndexFiles()) {
if (listAlreadyDownloaded.contains(fileItem.convertServerFileNameToLocal())) {
filtered.add(fileItem);
}
}
listAdapter.setIndexFiles(filtered);
} else if (item.getItemId() == DOWNLOAD_FILES_TYPE) {
if(type == DownloadActivityType.ROADS_FILE){
changeType(DownloadActivityType.NORMAL_FILE);
} else {
changeType(DownloadActivityType.ROADS_FILE);
}
} else if(item.getItemId() == DESELECT_ALL_ID){
entriesToDownload.clear();
listAdapter.notifyDataSetInvalidated();
@ -247,58 +253,29 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
return true;
}
private static class DownloadIndexListThread extends Thread {
private DownloadIndexActivity uiActivity = null;
private IndexFileList indexFiles = null;
private final Context ctx;
public DownloadIndexListThread(Context ctx){
super("DownloadIndexes");
this.ctx = ctx;
}
public void setUiActivity(DownloadIndexActivity uiActivity) {
this.uiActivity = uiActivity;
}
public Map<String, IndexItem> getCachedIndexFiles() {
return indexFiles != null ? indexFiles.getIndexFiles() : null;
}
public boolean isDownloadedFromInternet(){
return indexFiles != null && indexFiles.isDownloadedFromInternet();
}
@Override
public void run() {
indexFiles = DownloadOsmandIndexesHelper.getIndexesList(ctx);
if(uiActivity != null) {
uiActivity.removeDialog(DIALOG_PROGRESS_LIST);
uiActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (indexFiles != null) {
boolean basemapExists = ((OsmandApplication) uiActivity.getApplication()).getResourceManager().containsBasemap();
if(!basemapExists && indexFiles.getBasemap() != null) {
uiActivity.entriesToDownload.put(indexFiles.getBasemap().getFileName(),
indexFiles.getBasemap().createDownloadEntry(ctx));
AccessibleToast.makeText(uiActivity, R.string.basemap_was_selected_to_download,
Toast.LENGTH_LONG).show();
uiActivity.findViewById(R.id.DownloadButton).setVisibility(View.VISIBLE);
}
uiActivity.setListAdapter(uiActivity.new DownloadIndexAdapter(indexFiles.getIndexFiles()));
if (indexFiles.isIncreasedMapVersion()) {
uiActivity.showDialog(DownloadIndexActivity.DIALOG_MAP_VERSION_UPDATE);
}
} else {
AccessibleToast.makeText(uiActivity, R.string.list_index_files_was_not_loaded, Toast.LENGTH_LONG).show();
}
}
});
}
public void changeType(final DownloadActivityType tp) {
if (downloadListIndexThread != null) {
final List<IndexItem> filtered = getFilteredByType(tp);
entriesToDownload.clear();
((DownloadIndexAdapter) getExpandableListAdapter()).setIndexFiles(filtered);
type = tp;
}
}
private List<IndexItem> getFilteredByType(final DownloadActivityType tp) {
final List<IndexItem> filtered = new ArrayList<IndexItem>();
for (IndexItem file : downloadListIndexThread.getCachedIndexFiles()) {
if (file.getType() == tp) {
filtered.add(file);
}
}
return filtered;
}
@Override
protected Dialog onCreateDialog(int id) {
@ -417,7 +394,7 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
return true;
}
final DownloadEntry entry = e.createDownloadEntry(DownloadIndexActivity.this);
final DownloadEntry entry = e.createDownloadEntry(DownloadIndexActivity.this, type);
if (entry != null) {
// if(!fileToUnzip.exists()){
// builder.setMessage(MessageFormat.format(getString(R.string.download_question), baseName, extractDateAndSize(e.getValue())));
@ -432,7 +409,7 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
private Collection<String> listAlreadyDownloadedWithAlternatives() {
private Set<String> listAlreadyDownloadedWithAlternatives() {
Set<String> files = new TreeSet<String>();
File externalStorageDirectory = settings.getExternalStorageDirectory();
// files.addAll(listWithAlternatives(new File(externalStorageDirectory, ResourceManager.POI_PATH),POI_INDEX_EXT,POI_INDEX_EXT_ZIP,POI_TABLE_VERSION));
@ -451,9 +428,9 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
public boolean accept(File dir, String filename) {
if (filename.endsWith(ext)) {
files.add(filename);
files.add(filename.substring(0, filename.length() - ext.length()) + "_" + version + ext);
files.add(filename.substring(0, filename.length() - ext.length()) + ext);
if (secondaryExt != null) {
files.add(filename.substring(0, filename.length() - ext.length()) + "_" + version + secondaryExt);
files.add(filename.substring(0, filename.length() - ext.length()) + secondaryExt);
}
return true;
} else {
@ -523,8 +500,6 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
@ -538,51 +513,39 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
downloadListIndexThread.setUiActivity(null);
}
public class DownloadIndexesAsyncTask extends AsyncTask<String, Object, String> implements DownloadFileShowWarning {
private String convertServerFileNameToLocal(String name){
int l = name.lastIndexOf('_');
String s;
if(name.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT) || name.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT_ZIP)){
s = IndexConstants.BINARY_MAP_INDEX_EXT;
} else {
s = ""; //$NON-NLS-1$
}
return name.substring(0, l) + s;
}
private class DownloadIndexesAsyncTask extends AsyncTask<String, Object, String> implements DownloadFileShowWarning {
private IProgress progress;
private OsmandPreference<Integer> downloads;
public DownloadIndexesAsyncTask(ProgressDialogImplementation progressDialogImplementation) {
this.progress = progressDialogImplementation;
downloads = settings.NUMBER_OF_FREE_DOWNLOADS;
downloads = DownloadIndexActivity.this.getMyApplication().getSettings().NUMBER_OF_FREE_DOWNLOADS;
}
@Override
protected void onProgressUpdate(Object... values) {
for(Object o : values){
if(o instanceof DownloadEntry){
for (Object o : values) {
if (o instanceof DownloadEntry) {
String v = Version.getAppName(DownloadIndexActivity.this);
if(Version.isProductionVersion(DownloadIndexActivity.this)){
if (Version.isProductionVersion(DownloadIndexActivity.this)) {
v = Version.getFullVersion(DownloadIndexActivity.this);
} else {
v +=" test";
v += " test";
}
trackEvent(v, Version.getAppName(DownloadIndexActivity.this),
((DownloadEntry)o).baseName, 1, getString(R.string.ga_api_key));
updateLoadedFiles();
new DownloadTracker().trackEvent(DownloadIndexActivity.this, v, Version.getAppName(DownloadIndexActivity.this),
((DownloadEntry) o).baseName, 1, DownloadIndexActivity.this.getString(R.string.ga_api_key));
DownloadIndexActivity.this.updateLoadedFiles();
((DownloadIndexAdapter) getExpandableListAdapter()).notifyDataSetInvalidated();
findViewById(R.id.DownloadButton).setVisibility(
entriesToDownload.isEmpty() ? View.GONE : View.VISIBLE);
} else if(o instanceof String) {
findViewById(R.id.DownloadButton).setVisibility(entriesToDownload.isEmpty() ? View.GONE : View.VISIBLE);
} else if (o instanceof String) {
AccessibleToast.makeText(DownloadIndexActivity.this, (String) o, Toast.LENGTH_LONG).show();
}
}
super.onProgressUpdate(values);
}
@Override
protected void onPreExecute() {
downloadFileHelper.setInterruptDownloading(false);
@ -591,40 +554,38 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
mainView.setKeepScreenOn(true);
}
}
@Override
protected void onPostExecute(String result) {
if(result != null){
if (result != null) {
AccessibleToast.makeText(DownloadIndexActivity.this, result, Toast.LENGTH_LONG).show();
}
View mainView = findViewById(R.id.MainLayout);
if(mainView != null){
View mainView = DownloadIndexActivity.this.findViewById(R.id.MainLayout);
if (mainView != null) {
mainView.setKeepScreenOn(false);
}
updateLoadedFiles();
DownloadIndexActivity.this.updateLoadedFiles();
DownloadIndexAdapter adapter = ((DownloadIndexAdapter) getExpandableListAdapter());
if (adapter != null) {
adapter.notifyDataSetInvalidated();
}
}
@Override
protected String doInBackground(String... filesToDownload) {
try {
List<File> filesToReindex = new ArrayList<File>();
boolean forceWifi = downloadFileHelper.isWifiConnected();
boolean forceWifi = DownloadIndexActivity.this.downloadFileHelper.isWifiConnected();
for (int i = 0; i < filesToDownload.length; i++) {
String filename = filesToDownload[i];
DownloadEntry entry = entriesToDownload.get(filename);
DownloadEntry entry = DownloadIndexActivity.this.entriesToDownload.get(filename);
if (entry != null) {
String indexOfAllFiles = filesToDownload.length <= 1 ? "" : (" [" + (i + 1) + "/"
+ filesToDownload.length + "]");
boolean result = entry.downloadFile(downloadFileHelper, filename, filesToReindex, progress, indexOfAllFiles, this, forceWifi, getAssets());
String indexOfAllFiles = filesToDownload.length <= 1 ? "" : (" [" + (i + 1) + "/" + filesToDownload.length + "]");
boolean result = downloadFile(entry, filename, filesToReindex, indexOfAllFiles, forceWifi);
if (result) {
entriesToDownload.remove(filename);
DownloadIndexActivity.this.entriesToDownload.remove(filename);
downloads.set(downloads.get() + 1);
if(entry.existingBackupFile != null) {
if (entry.existingBackupFile != null) {
Algoritms.removeAllFiles(entry.existingBackupFile);
}
publishProgress(entry);
@ -650,9 +611,9 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
} catch (InterruptedException e) {
// do not dismiss dialog
} finally {
if (progressFileDlg != null) {
removeDialog(DIALOG_PROGRESS_FILE);
progressFileDlg = null;
if (DownloadIndexActivity.this.progressFileDlg != null) {
removeDialog(DownloadIndexActivity.DIALOG_PROGRESS_FILE);
DownloadIndexActivity.this.progressFileDlg = null;
}
}
return null;
@ -661,461 +622,27 @@ public class DownloadIndexActivity extends OsmandExpandableListActivity {
@Override
public void showWarning(String warning) {
publishProgress(warning);
}
}
public static class DownloadEntry {
public File fileToSave;
public File fileToUnzip;
public boolean unzip;
public Long dateModified;
public double sizeMB;
public String baseName;
public int parts;
public File existingBackupFile;
public DownloadEntry attachedEntry;
public boolean isAsset;
public DownloadEntry() {
// default
}
public DownloadEntry(String assetName, String fileName, long dateModified) {
this.dateModified = dateModified;
fileToUnzip = new File(fileName);
fileToSave = new File(assetName);
isAsset = true;
}
public boolean downloadFile(DownloadFileHelper downloadFileHelper, String filename, List<File> filesToReindex,
IProgress progress, String indexOfAllFiles, DownloadIndexesAsyncTask downloadIndexesAsyncTask,
boolean forceWifi, AssetManager assetManager)
public boolean downloadFile(DownloadEntry de, String filename, List<File> filesToReindex, String indexOfAllFiles, boolean forceWifi)
throws InterruptedException {
boolean res = false;
if (isAsset) {
if (de.isAsset) {
try {
ResourceManager.copyAssets(assetManager, fileToSave.getPath(), fileToUnzip);
fileToUnzip.setLastModified(this.dateModified);
ResourceManager.copyAssets(getAssets(), de.fileToSave.getPath(), de.fileToUnzip);
de.fileToUnzip.setLastModified(de.dateModified);
res = true;
} catch (IOException e) {
log.error("Copy exception", e);
}
} else {
res = downloadFileHelper.downloadFile(filename, fileToSave, fileToUnzip, unzip, progress, dateModified, parts,
filesToReindex, indexOfAllFiles, downloadIndexesAsyncTask, forceWifi);
res = downloadFileHelper.downloadFile(filename, de, progress, filesToReindex, indexOfAllFiles, this, forceWifi);
}
if (res && attachedEntry != null) {
return attachedEntry.downloadFile(downloadFileHelper, filename, filesToReindex, progress, indexOfAllFiles,
downloadIndexesAsyncTask, forceWifi, assetManager);
if (res && de.attachedEntry != null) {
return downloadFile(de.attachedEntry, filename, filesToReindex, indexOfAllFiles, forceWifi);
}
return res;
}
}
private static class IndexItemCategory implements Comparable<IndexItemCategory> {
public final String name;
public final List<IndexItem> items = new ArrayList<IndexItem>();
private final int order;
public IndexItemCategory(String name, int order) {
this.name = name;
this.order = order;
}
@Override
public int compareTo(IndexItemCategory another) {
return order < another.order ? -1 : 1;
}
}
public List<IndexItemCategory> categorizeIndexItems(Collection<IndexItem> indexItems) {
final Map<String, IndexItemCategory> cats = new TreeMap<String, DownloadIndexActivity.IndexItemCategory>();
for(IndexItem i : indexItems){
int nameId = R.string.index_name_other;
int order = 0;
String lc = i.getFileName().toLowerCase();
if(lc.endsWith(".voice.zip")) {
nameId = R.string.index_name_voice;
order = 1;
} else if(lc.contains(".ttsvoice.zip")) {
nameId = R.string.index_name_tts_voice;
order = 2;
} else if(lc.startsWith("us")) {
nameId = R.string.index_name_us;
order = 31;
} else if(lc.contains("_northamerica_")) {
nameId = R.string.index_name_north_america;
order = 30;
} else if(lc.contains("_centralamerica_") || lc.contains("central-america")) {
nameId = R.string.index_name_central_america;
order = 40;
} else if(lc.contains("_southamerica_") || lc.contains("south-america")) {
nameId = R.string.index_name_south_america;
order = 45;
} else if(lc.startsWith("france_")) {
nameId = R.string.index_name_france;
order = 17;
} else if(lc.startsWith("germany_")) {
nameId = R.string.index_name_germany;
order = 16;
} else if(lc.contains("_europe_")) {
nameId = R.string.index_name_europe;
order = 15;
} else if(lc.startsWith("russia_")) {
nameId = R.string.index_name_russia;
order = 18;
} else if(lc.contains("africa")) {
nameId = R.string.index_name_africa;
order = 80;
} else if(lc.contains("_asia_")) {
nameId = R.string.index_name_asia;
order = 50;
} else if(lc.contains("_oceania_") || lc.contains("australia") ) {
nameId = R.string.index_name_oceania;
order = 70;
} else if(lc.contains("_wiki_")) {
nameId = R.string.index_name_wiki;
order = 10;
}
String name = getString(nameId);
if (!cats.containsKey(name)) {
cats.put(name, new IndexItemCategory(name, order));
}
cats.get(name).items.add(i);
}
ArrayList<IndexItemCategory> r = new ArrayList<DownloadIndexActivity.IndexItemCategory>(cats.values());
Collections.sort(r);
return r;
}
protected class DownloadIndexAdapter extends OsmandBaseExpandableListAdapter implements Filterable {
private DownloadIndexFilter myFilter;
private final Map<String, IndexItem> indexFiles;
private final List<IndexItemCategory> list = new ArrayList<IndexItemCategory>();
public DownloadIndexAdapter(Map<String, IndexItem> indexFiles) {
this.indexFiles = new LinkedHashMap<String, IndexItem>(indexFiles);
List<IndexItemCategory> cats = categorizeIndexItems(indexFiles.values());
synchronized (this) {
list.clear();
list.addAll(cats);
}
getFilter().filter(filterText.getText());
}
public void collapseTrees(final CharSequence constraint){
runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (DownloadIndexAdapter.this) {
final ExpandableListView expandableListView = getExpandableListView();
for (int i = 0; i < getGroupCount(); i++) {
int cp = getChildrenCount(i);
if (cp < 7) {
expandableListView.expandGroup(i);
} else {
expandableListView.collapseGroup(i);
}
}
}
}
});
}
public Map<String, IndexItem> getIndexFiles() {
return indexFiles;
}
public void setIndexFiles(List<IndexItem> indexFiles) {
this.indexFiles.clear();
for(IndexItem i : indexFiles) {
this.indexFiles.put(i.getFileName(), i);
}
List<IndexItemCategory> cats = categorizeIndexItems(indexFiles);
synchronized (this) {
list.clear();
list.addAll(cats);
}
notifyDataSetChanged();
}
@Override
public Filter getFilter() {
if (myFilter == null) {
myFilter = new DownloadIndexFilter();
}
return myFilter;
}
private final class DownloadIndexFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
results.values = indexFiles.values();
results.count = indexFiles.size();
} else {
String[] vars = constraint.toString().split("\\s");
for(int i=0; i< vars.length; i++){
vars[i] = vars[i].trim().toLowerCase();
}
List<IndexItem> filter = new ArrayList<IndexItem>();
for (IndexItem item : indexFiles.values()) {
boolean add = true;
for (String var : vars) {
if (var.length() > 0) {
if (!item.getVisibleName().toLowerCase().contains(var)
&& !item.getDescription().toLowerCase().contains(var)) {
add = false;
}
}
}
if(add){
filter.add(item);
}
}
results.values = filter;
results.count = filter.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
synchronized (DownloadIndexAdapter.this) {
list.clear();
Collection<IndexItem> items = (Collection<IndexItem>) results.values;
if (items != null && !items.isEmpty()) {
list.addAll(categorizeIndexItems(items));
} else {
list.add(new IndexItemCategory(getResources().getString(R.string.select_index_file_to_download), 1));
}
}
notifyDataSetChanged();
collapseTrees(constraint);
}
}
@Override
public int getGroupCount() {
return list.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return list.get(groupPosition).items.size();
}
@Override
public IndexItemCategory getGroup(int groupPosition) {
return list.get(groupPosition);
}
@Override
public IndexItem getChild(int groupPosition, int childPosition) {
return list.get(groupPosition).items.get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition + (childPosition + 1)* 10000;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
IndexItemCategory group = getGroup(groupPosition);
if (v == null) {
LayoutInflater inflater = getLayoutInflater();
v = inflater.inflate(net.osmand.plus.R.layout.download_index_list_item_category, parent, false);
}
final View row = v;
TextView item = (TextView) row.findViewById(R.id.download_index_category_name);
item.setText(group.name);
item.setLinkTextColor(Color.YELLOW);
adjustIndicator(groupPosition, isExpanded, v);
return row;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = getLayoutInflater();
v = inflater.inflate(net.osmand.plus.R.layout.download_index_list_item, parent, false);
}
final View row = v;
TextView item = (TextView) row.findViewById(R.id.download_item);
TextView description = (TextView) row.findViewById(R.id.download_descr);
IndexItem e = (IndexItem) getChild(groupPosition, childPosition);
item.setText((e.getVisibleDescription(DownloadIndexActivity.this) + "\n" + e.getVisibleName()).trim()); //$NON-NLS-1$
description.setText(e.getDate() + "\n" + e.getSize() + " MB");
CheckBox ch = (CheckBox) row.findViewById(R.id.check_download_item);
ch.setChecked(entriesToDownload.containsKey(e.getFileName()));
ch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CheckBox ch = (CheckBox) v.findViewById(R.id.check_download_item);
ch.setChecked(!ch.isChecked());
DownloadIndexActivity.this.onChildClick(getListView(), row, groupPosition, childPosition, getChildId(groupPosition, childPosition));
}
});
if(indexFileNames != null){
String sfName = convertServerFileNameToLocal(e.getFileName());
if(!indexFileNames.containsKey(sfName)){
item.setTextColor(getResources().getColor(R.color.index_unknown));
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
} else {
if(e.getDate() != null){
if(e.getDate().equals(indexActivatedFileNames.get(sfName))){
item.setText(item.getText() + "\n" + getResources().getString(R.string.local_index_installed) + " : " + indexActivatedFileNames.get(sfName));
item.setTextColor(getResources().getColor(R.color.act_index_uptodate)); //GREEN
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
} else if (e.getDate().equals(indexFileNames.get(sfName))) {
item.setText(item.getText() + "\n" + getResources().getString(R.string.local_index_installed) + " : " + indexFileNames.get(sfName));
//item.setTextColor(getResources().getColor(R.color.deact_index_uptodate)); //DARK_GREEN
// Try fix Issue 1482: Use italic instead of dark colors for deactivated maps
item.setTextColor(getResources().getColor(R.color.act_index_uptodate));
item.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
} else if (indexActivatedFileNames.containsKey(sfName)) {
item.setText(item.getText() + "\n" + getResources().getString(R.string.local_index_installed) + " : " + indexActivatedFileNames.get(sfName));
item.setTextColor(getResources().getColor(R.color.act_index_updateable)); //LIGHT_BLUE
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
} else {
item.setText(item.getText() + "\n" + getResources().getString(R.string.local_index_installed) + " : " + indexFileNames.get(sfName));
//item.setTextColor(getResources().getColor(R.color.deact_index_updateable)); //DARK_BLUE
// Try fix Issue 1482: Use italic instead of dark colors for deactivated maps
item.setTextColor(getResources().getColor(R.color.act_index_updateable));
item.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
}
} else {
item.setTextColor(getResources().getColor(R.color.act_index_uptodate));
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
}
}
}
return row;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
private Map<String, String> getCustomVars(){
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("App", Version.getFullVersion(this));
map.put("Device", Build.DEVICE);
map.put("Brand", Build.BRAND);
map.put("Model", Build.MODEL);
map.put("Package", getPackageName());
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
if (info != null) {
map.put("Version name", info.versionName);
map.put("Version code", info.versionCode+"");
}
} catch (NameNotFoundException e) {
}
return map;
}
private String randomNumber() {
return (new Random(System.currentTimeMillis()).nextInt(100000000) + 100000000) + "";
}
final String beaconUrl = "http://www.google-analytics.com/__utm.gif";
final String analyticsVersion = "4.3"; // Analytics version - AnalyticsVersion
public void trackEvent(String category, String action, String label, int value, String trackingAcount) {
Map<String, String> parameters = new LinkedHashMap<String, String>();
try {
Map<String, String> customVariables = getCustomVars();
parameters.put("AnalyticsVersion", analyticsVersion);
parameters.put("utmn", randomNumber());
parameters.put("utmhn", "http://app.osmand.net");
parameters.put("utmni", "1");
parameters.put("utmt", "event");
StringBuilder customVars = new StringBuilder();
Iterator<Entry<String, String>> customs = customVariables.entrySet().iterator();
for (int i = 0; i < customVariables.size(); i++) {
Entry<String, String> n = customs.next();
if (i > 0) {
customVars.append("*");
}
// "'" => "'0", ')' => "'1", '*' => "'2", '!' => "'3",
customVars.append((i + 1) + "!").append((n.getKey() + n.getValue()));
}
parameters.put("utmcs", "UTF-8");
parameters.put("utmul", "en");
parameters.put("utmhid", (System.currentTimeMillis()/ 1000) + "");
parameters.put("utmac", trackingAcount);
String domainHash = "app.osmand.net".hashCode()+"";
String utma = domainHash + ".";
File fl = getMyApplication().getSettings().extendOsmandPath(ResourceManager.APP_DIR + ".nomedia");
if(fl.exists()) {
utma += (fl.lastModified())+ ".";
} else {
utma += (randomNumber())+ ".";
}
utma += ((System.currentTimeMillis()/ 1000) + ".");
utma += ((System.currentTimeMillis()/ 1000) + ".");
utma += ((System.currentTimeMillis()/ 1000) + ".");
utma += "1";
parameters.put("utmcc", "__utma=" + utma + ";");
parameters.put("utme", MessageFormat.format("5({0}*{1}*{2})({3})", category, action, label == null ? "" : label, value)
+ customVars);
StringBuilder urlString = new StringBuilder(beaconUrl + "?");
Iterator<Entry<String, String>> it = parameters.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
urlString.append(e.getKey()).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8"));
if (it.hasNext()) {
urlString.append("&");
}
}
log.debug(urlString);
URL url = new URL(urlString.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setDoInput(false);
conn.setDoOutput(false);
conn.connect();
log.info("Response analytics is " + conn.getResponseCode() + " " + conn.getResponseMessage());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}

View file

@ -17,7 +17,7 @@ public abstract class OsmandExpandableListActivity extends
view.setDivider(getResources().getDrawable(R.drawable.tab_text_separator));
}
protected OsmandApplication getMyApplication() {
public OsmandApplication getMyApplication() {
return (OsmandApplication)getApplication();
}
}

View file

@ -0,0 +1,29 @@
package net.osmand.plus.download;
import java.io.File;
public class DownloadEntry {
public File fileToSave;
public File fileToUnzip;
public boolean unzip;
public Long dateModified;
public double sizeMB;
public String baseName;
public int parts;
public File existingBackupFile;
public DownloadEntry attachedEntry;
public boolean isAsset;
public boolean isRoadMap;
public DownloadEntry() {
// default
}
public DownloadEntry(String assetName, String fileName, long dateModified) {
this.dateModified = dateModified;
fileToUnzip = new File(fileName);
fileToSave = new File(assetName);
isAsset = true;
}
}

View file

@ -1,7 +1,8 @@
package net.osmand.plus.activities;
package net.osmand.plus.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ -46,7 +47,6 @@ public class DownloadFileHelper {
protected void downloadFile(String fileName, FileOutputStream out, URL url, String part, String indexOfAllFiles,
IProgress progress, boolean forceWifi) throws IOException, InterruptedException {
InputStream is = null;
byte[] buffer = new byte[BUFFER_SIZE];
int read = 0;
int length = 0;
@ -128,21 +128,26 @@ public class DownloadFileHelper {
return ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI;
}
protected boolean downloadFile(final String fileName, final File fileToDownload, final File fileToUnZip, final boolean unzipToDir,
IProgress progress, Long dateModified, int parts, List<File> toReIndex, String indexOfAllFiles,
DownloadFileShowWarning showWarningCallback, boolean forceWifi ) throws InterruptedException {
public boolean downloadFile(final String fileName, DownloadEntry de, IProgress progress,
List<File> toReIndex, String indexOfAllFiles,
DownloadFileShowWarning showWarningCallback, boolean forceWifi) throws InterruptedException {
FileOutputStream out = null;
try {
out = new FileOutputStream(fileToDownload);
out = new FileOutputStream(de.fileToSave);
try {
if(parts == 1){
URL url = new URL("http://download.osmand.net/download?event=2&file="+fileName + "&" + Version.getVersionAsURLParam(ctx)); //$NON-NLS-1$
String urlPrefix = "http://download.osmand.net/download?event=2&file=";
String urlSuffix = "&" + Version.getVersionAsURLParam(ctx);
if(de.isRoadMap) {
urlSuffix += "&road=yes";
}
if (de.parts == 1) {
URL url = new URL(urlPrefix + fileName + urlSuffix); //$NON-NLS-1$
downloadFile(fileName, out, url, null, indexOfAllFiles, progress, forceWifi);
} else {
for(int i=1; i<=parts; i++){
URL url = new URL("http://download.osmand.net/download?event=2&file="+fileName+"-"+i + "&" + Version.getVersionAsURLParam(ctx)); //$NON-NLS-1$
downloadFile(fileName, out, url, " ["+i+"/"+parts+"]", indexOfAllFiles, progress, forceWifi);
for (int i = 1; i <= de.parts; i++) {
URL url = new URL(urlPrefix + fileName + "-" + i + urlSuffix); //$NON-NLS-1$
downloadFile(fileName, out, url, " [" + i + "/" + de.parts + "]", indexOfAllFiles, progress, forceWifi);
}
}
} finally {
@ -150,81 +155,86 @@ public class DownloadFileHelper {
out = null;
}
if (fileToDownload.getName().endsWith(".zip")) { //$NON-NLS-1$
if (unzipToDir) {
fileToUnZip.mkdirs();
}
CountingInputStream fin = new CountingInputStream(new FileInputStream(fileToDownload));
ZipInputStream zipIn = new ZipInputStream(fin);
ZipEntry entry = null;
boolean first = true;
int len = (int) fileToDownload.length();
progress.startTask(ctx.getString(R.string.unzipping_file), len / 1024);
while ((entry = zipIn.getNextEntry()) != null) {
if(entry.isDirectory() || entry.getName().endsWith(IndexConstants.GEN_LOG_EXT)){
continue;
}
File fs;
if (!unzipToDir) {
if (first) {
fs = fileToUnZip;
first = false;
} else {
String name = entry.getName();
// small simplification
int ind = name.lastIndexOf('_');
if (ind > 0) {
// cut version
int i = name.indexOf('.', ind);
if (i > 0) {
name = name.substring(0, ind) + name.substring(i, name.length());
}
}
fs = new File(fileToUnZip.getParent(), name);
}
} else {
fs = new File(fileToUnZip, entry.getName());
}
out = new FileOutputStream(fs);
int read;
byte[] buffer = new byte[BUFFER_SIZE];
int remaining = len;
while ((read = zipIn.read(buffer)) != -1) {
out.write(buffer, 0, read);
remaining -= fin.lastReadCount();
progress.remaining(remaining / 1024);
}
out.close();
if(dateModified != null){
fs.setLastModified(dateModified);
}
toReIndex.add(fs);
}
zipIn.close();
fileToDownload.delete(); // zip is no needed more
}
unzipFile(de, progress, toReIndex);
showWarningCallback.showWarning(ctx.getString(R.string.download_index_success));
return true;
} catch (IOException e) {
log.error("Exception ocurred", e); //$NON-NLS-1$
showWarningCallback.showWarning(ctx.getString(R.string.error_io_error));
if(out != null){
if (out != null) {
try {
out.close();
} catch (IOException e1) {
}
}
// Possibly file is corrupted
fileToDownload.delete();
de.fileToSave.delete();
return false;
} catch (InterruptedException e) {
// Possibly file is corrupted
fileToDownload.delete();
de.fileToSave.delete();
throw e;
}
}
private void unzipFile(DownloadEntry de, IProgress progress, List<File> toReIndex)
throws FileNotFoundException, IOException {
if (de.fileToSave.getName().endsWith(".zip")) { //$NON-NLS-1$
if (de.unzip) {
de.fileToUnzip.mkdirs();
}
CountingInputStream fin = new CountingInputStream(new FileInputStream(de.fileToSave));
ZipInputStream zipIn = new ZipInputStream(fin);
ZipEntry entry = null;
boolean first = true;
int len = (int) de.fileToSave.length();
progress.startTask(ctx.getString(R.string.unzipping_file), len / 1024);
while ((entry = zipIn.getNextEntry()) != null) {
if (entry.isDirectory() || entry.getName().endsWith(IndexConstants.GEN_LOG_EXT)) {
continue;
}
File fs;
if (!de.unzip) {
if (first) {
fs = de.fileToUnzip;
first = false;
} else {
String name = entry.getName();
// small simplification
int ind = name.lastIndexOf('_');
if (ind > 0) {
// cut version
int i = name.indexOf('.', ind);
if (i > 0) {
name = name.substring(0, ind) + name.substring(i, name.length());
}
}
fs = new File(de.fileToUnzip.getParent(), name);
}
} else {
fs = new File(de.fileToUnzip, entry.getName());
}
FileOutputStream out = new FileOutputStream(fs);
int read;
byte[] buffer = new byte[BUFFER_SIZE];
int remaining = len;
while ((read = zipIn.read(buffer)) != -1) {
out.write(buffer, 0, read);
remaining -= fin.lastReadCount();
progress.remaining(remaining / 1024);
}
out.close();
if (de.dateModified != null) {
fs.setLastModified(de.dateModified);
}
toReIndex.add(fs);
}
zipIn.close();
de.fileToSave.delete(); // zip is no needed more
}
}
public void setInterruptDownloading(boolean interruptDownloading) {

View file

@ -0,0 +1,273 @@
package net.osmand.plus.download;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import net.osmand.data.IndexConstants;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.DownloadIndexActivity;
import net.osmand.plus.activities.OsmandBaseExpandableListAdapter;
import net.osmand.plus.activities.DownloadIndexActivity.DownloadActivityType;
import net.osmand.plus.download.DownloadOsmandIndexesHelper.IndexItem;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
public class DownloadIndexAdapter extends OsmandBaseExpandableListAdapter implements Filterable {
private DownloadIndexFilter myFilter;
private final List<IndexItem> indexFiles;
private final List<IndexItemCategory> list = new ArrayList<IndexItemCategory>();
private DownloadIndexActivity downloadActivity;
private Map<String, String> indexFileNames = null;
private Map<String, String> indexActivatedFileNames = null;
public DownloadIndexAdapter(DownloadIndexActivity downloadActivity, List<IndexItem> indexFiles) {
this.downloadActivity = downloadActivity;
this.indexFiles = new ArrayList<IndexItem>(indexFiles);
List<IndexItemCategory> cats = IndexItemCategory.categorizeIndexItems(downloadActivity, indexFiles);
synchronized (this) {
list.clear();
list.addAll(cats);
}
updateLoadedFiles();
}
public void updateLoadedFiles() {
indexActivatedFileNames = getMyApplication().getResourceManager().getIndexFileNames();
indexFileNames = getMyApplication().getResourceManager().getIndexFileNames();
getMyApplication().getResourceManager().getBackupIndexes(indexFileNames);
}
private OsmandApplication getMyApplication() {
return (OsmandApplication) downloadActivity.getApplication();
}
public void collapseTrees(final CharSequence constraint) {
downloadActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
synchronized (DownloadIndexAdapter.this) {
final ExpandableListView expandableListView = downloadActivity.getExpandableListView();
for (int i = 0; i < getGroupCount(); i++) {
int cp = getChildrenCount(i);
if (cp < 7) {
expandableListView.expandGroup(i);
} else {
expandableListView.collapseGroup(i);
}
}
}
}
});
}
public List<IndexItem> getIndexFiles() {
return indexFiles;
}
public void setIndexFiles(List<IndexItem> indexFiles) {
this.indexFiles.clear();
for (IndexItem i : indexFiles) {
this.indexFiles.add(i);
}
List<IndexItemCategory> cats = IndexItemCategory.categorizeIndexItems(downloadActivity, indexFiles);
synchronized (this) {
list.clear();
list.addAll(cats);
}
notifyDataSetChanged();
}
@Override
public Filter getFilter() {
if (myFilter == null) {
myFilter = new DownloadIndexFilter();
}
return myFilter;
}
private final class DownloadIndexFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint == null || constraint.length() == 0) {
results.values = indexFiles;
results.count = indexFiles.size();
} else {
String[] vars = constraint.toString().split("\\s");
for (int i = 0; i < vars.length; i++) {
vars[i] = vars[i].trim().toLowerCase();
}
List<IndexItem> filter = new ArrayList<IndexItem>();
for (IndexItem item : indexFiles) {
boolean add = true;
for (String var : vars) {
if (var.length() > 0) {
if (!item.getVisibleName().toLowerCase().contains(var) && !item.getDescription().toLowerCase().contains(var)) {
add = false;
}
}
}
if (add) {
filter.add(item);
}
}
results.values = filter;
results.count = filter.size();
}
return results;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
synchronized (DownloadIndexAdapter.this) {
list.clear();
Collection<IndexItem> items = (Collection<IndexItem>) results.values;
if (items != null && !items.isEmpty()) {
list.addAll(IndexItemCategory.categorizeIndexItems(downloadActivity, items));
} else {
list.add(new IndexItemCategory(downloadActivity.getResources().getString(R.string.select_index_file_to_download), 1));
}
}
notifyDataSetChanged();
collapseTrees(constraint);
}
}
@Override
public int getGroupCount() {
return list.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return list.get(groupPosition).items.size();
}
@Override
public IndexItemCategory getGroup(int groupPosition) {
return list.get(groupPosition);
}
@Override
public IndexItem getChild(int groupPosition, int childPosition) {
return list.get(groupPosition).items.get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return groupPosition + (childPosition + 1) * 10000;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
IndexItemCategory group = getGroup(groupPosition);
if (v == null) {
LayoutInflater inflater = downloadActivity.getLayoutInflater();
v = inflater.inflate(net.osmand.plus.R.layout.download_index_list_item_category, parent, false);
}
final View row = v;
TextView item = (TextView) row.findViewById(R.id.download_index_category_name);
item.setText(group.name);
item.setLinkTextColor(Color.YELLOW);
adjustIndicator(groupPosition, isExpanded, v);
return row;
}
@Override
public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = downloadActivity.getLayoutInflater();
v = inflater.inflate(net.osmand.plus.R.layout.download_index_list_item, parent, false);
}
final View row = v;
TextView item = (TextView) row.findViewById(R.id.download_item);
TextView description = (TextView) row.findViewById(R.id.download_descr);
IndexItem e = (IndexItem) getChild(groupPosition, childPosition);
item.setText((e.getVisibleDescription(downloadActivity, downloadActivity.getType()) + "\n" + e.getVisibleName()).trim()); //$NON-NLS-1$
description.setText(e.getDate() + "\n" + e.getSize() + " MB");
CheckBox ch = (CheckBox) row.findViewById(R.id.check_download_item);
ch.setChecked(downloadActivity.getEntriesToDownload().containsKey(e.getFileName()));
ch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final CheckBox ch = (CheckBox) v.findViewById(R.id.check_download_item);
ch.setChecked(!ch.isChecked());
downloadActivity.onChildClick(downloadActivity.getListView(), row, groupPosition, childPosition, getChildId(groupPosition, childPosition));
}
});
if (indexFileNames != null) {
String sfName = e.convertServerFileNameToLocal();
if (!indexFileNames.containsKey(sfName)) {
item.setTextColor(downloadActivity.getResources().getColor(R.color.index_unknown));
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
} else {
if (e.getDate() != null) {
if (e.getDate().equals(indexActivatedFileNames.get(sfName))) {
item.setText(item.getText() + "\n" + downloadActivity.getResources().getString(R.string.local_index_installed) + " : "
+ indexActivatedFileNames.get(sfName));
item.setTextColor(downloadActivity.getResources().getColor(R.color.act_index_uptodate)); // GREEN
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
} else if (e.getDate().equals(indexFileNames.get(sfName))) {
item.setText(item.getText() + "\n" + downloadActivity.getResources().getString(R.string.local_index_installed) + " : "
+ indexFileNames.get(sfName));
// item.setTextColor(getResources().getColor(R.color.deact_index_uptodate)); //DARK_GREEN
// Try fix Issue 1482: Use italic instead of dark colors for deactivated maps
item.setTextColor(downloadActivity.getResources().getColor(R.color.act_index_uptodate));
item.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
} else if (indexActivatedFileNames.containsKey(sfName)) {
item.setText(item.getText() + "\n" + downloadActivity.getResources().getString(R.string.local_index_installed) + " : "
+ indexActivatedFileNames.get(sfName));
item.setTextColor(downloadActivity.getResources().getColor(R.color.act_index_updateable)); // LIGHT_BLUE
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
} else {
item.setText(item.getText() + "\n" + downloadActivity.getResources().getString(R.string.local_index_installed) + " : "
+ indexFileNames.get(sfName));
// item.setTextColor(getResources().getColor(R.color.deact_index_updateable)); //DARK_BLUE
// Try fix Issue 1482: Use italic instead of dark colors for deactivated maps
item.setTextColor(downloadActivity.getResources().getColor(R.color.act_index_updateable));
item.setTypeface(Typeface.DEFAULT, Typeface.ITALIC);
}
} else {
item.setTextColor(downloadActivity.getResources().getColor(R.color.act_index_uptodate));
item.setTypeface(Typeface.DEFAULT, Typeface.NORMAL);
}
}
}
return row;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}

View file

@ -0,0 +1,66 @@
package net.osmand.plus.download;
import java.util.List;
import java.util.Map;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.R;
import net.osmand.plus.activities.DownloadIndexActivity;
import net.osmand.plus.activities.DownloadIndexActivity.DownloadActivityType;
import net.osmand.plus.download.DownloadOsmandIndexesHelper.IndexItem;
import android.content.Context;
import android.view.View;
import android.widget.Toast;
public class DownloadIndexListThread extends Thread {
private DownloadIndexActivity uiActivity = null;
private IndexFileList indexFiles = null;
private final Context ctx;
public DownloadIndexListThread(Context ctx) {
super("DownloadIndexes");
this.ctx = ctx;
}
public void setUiActivity(DownloadIndexActivity uiActivity) {
this.uiActivity = uiActivity;
}
public List<IndexItem> getCachedIndexFiles() {
return indexFiles != null ? indexFiles.getIndexFiles() : null;
}
public boolean isDownloadedFromInternet() {
return indexFiles != null && indexFiles.isDownloadedFromInternet();
}
@Override
public void run() {
indexFiles = DownloadOsmandIndexesHelper.getIndexesList(ctx);
if (uiActivity != null) {
uiActivity.removeDialog(DownloadIndexActivity.DIALOG_PROGRESS_LIST);
uiActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
if (indexFiles != null) {
boolean basemapExists = ((OsmandApplication) uiActivity.getApplication()).getResourceManager().containsBasemap();
if (!basemapExists && indexFiles.getBasemap() != null) {
uiActivity.getEntriesToDownload().put(indexFiles.getBasemap().getFileName(), indexFiles.getBasemap()
.createDownloadEntry(ctx, uiActivity.getType()));
AccessibleToast.makeText(uiActivity, R.string.basemap_was_selected_to_download, Toast.LENGTH_LONG).show();
uiActivity.findViewById(R.id.DownloadButton).setVisibility(View.VISIBLE);
}
uiActivity.setListAdapter(new DownloadIndexAdapter(uiActivity, indexFiles.getIndexFiles()));
if (indexFiles.isIncreasedMapVersion()) {
uiActivity.showDialog(DownloadIndexActivity.DIALOG_MAP_VERSION_UPDATE);
}
} else {
AccessibleToast.makeText(uiActivity, R.string.list_index_files_was_not_loaded, Toast.LENGTH_LONG).show();
}
}
});
}
}
}

View file

@ -1,4 +1,4 @@
package net.osmand.plus;
package net.osmand.plus.download;
import static net.osmand.data.IndexConstants.BINARY_MAP_INDEX_EXT;
import static net.osmand.data.IndexConstants.BINARY_MAP_INDEX_EXT_ZIP;
@ -16,7 +16,11 @@ import net.osmand.LogUtil;
import net.osmand.Version;
import net.osmand.access.AccessibleToast;
import net.osmand.data.IndexConstants;
import net.osmand.plus.activities.DownloadIndexActivity.DownloadEntry;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.OsmandSettings;
import net.osmand.plus.R;
import net.osmand.plus.ResourceManager;
import net.osmand.plus.activities.DownloadIndexActivity.DownloadActivityType;
import org.apache.commons.logging.Log;
import org.xmlpull.v1.XmlPullParser;
@ -72,10 +76,10 @@ public class DownloadOsmandIndexesHelper {
File destFile = new File(voicePath, voice + File.separatorChar + "_ttsconfig.p");
String key = voice + ext;
String assetName = "voice" + File.separatorChar + voice + File.separatorChar + "ttsconfig.p";
result.add(key, new AssetIndexItem(key, "voice", date, dateModified, "0.1", "", assetName, destFile.getPath()));
result.add(new AssetIndexItem(key, "voice", date, dateModified, "0.1", "", assetName, destFile.getPath()));
} else {
String key = voice + extvoice;
IndexItem item = result.getIndexFiles().get(key);
IndexItem item = result.getIndexFilesByName(key);
if (item != null) {
File destFile = new File(voicePath, voice + File.separatorChar + "_config.p");
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy"); //$NON-NLS-1$
@ -93,10 +97,21 @@ public class DownloadOsmandIndexesHelper {
}
}
}
result.sort();
} catch (IOException e) {
log.error("Error while loading tts files from assets", e); //$NON-NLS-1$
}
}
private static DownloadActivityType getIndexType(String tagName){
if("region".equals(tagName) ||
"multiregion".equals(tagName)) {
return DownloadActivityType.NORMAL_FILE;
} else if("road_region".equals(tagName) ) {
return DownloadActivityType.ROADS_FILE;
}
return null;
}
private static IndexFileList downloadIndexesListFromInternet(String versionAsUrl){
try {
@ -109,19 +124,24 @@ public class DownloadOsmandIndexesHelper {
parser.setInput(url.openStream(), "UTF-8"); //$NON-NLS-1$
int next;
while((next = parser.next()) != XmlPullParser.END_DOCUMENT) {
if(next == XmlPullParser.START_TAG && ("region".equals(parser.getName()) ||
"multiregion".equals(parser.getName()))) { //$NON-NLS-1$
String name = parser.getAttributeValue(null, "name"); //$NON-NLS-1$
String size = parser.getAttributeValue(null, "size"); //$NON-NLS-1$
String date = parser.getAttributeValue(null, "date"); //$NON-NLS-1$
String description = parser.getAttributeValue(null, "description"); //$NON-NLS-1$
String parts = parser.getAttributeValue(null, "parts"); //$NON-NLS-1$
result.add(name, new IndexItem(name, description, date, size, parts));
} else if (next == XmlPullParser.START_TAG && ("osmand_regions".equals(parser.getName()))) {
String mapversion = parser.getAttributeValue(null, "mapversion");
result.setMapVersion(mapversion);
}
if (next == XmlPullParser.START_TAG) {
DownloadActivityType tp = getIndexType(parser.getName());
if (tp != null) {
String name = parser.getAttributeValue(null, "name"); //$NON-NLS-1$
String size = parser.getAttributeValue(null, "size"); //$NON-NLS-1$
String date = parser.getAttributeValue(null, "date"); //$NON-NLS-1$
String description = parser.getAttributeValue(null, "description"); //$NON-NLS-1$
String parts = parser.getAttributeValue(null, "parts"); //$NON-NLS-1$
IndexItem it = new IndexItem(name, description, date, size, parts);
it.setType(tp);
result.add(it);
} else if ("osmand_regions".equals(parser.getName())) {
String mapversion = parser.getAttributeValue(null, "mapversion");
result.setMapVersion(mapversion);
}
}
}
result.sort();
} catch (IOException e) {
log.error("Error while loading indexes from repository", e); //$NON-NLS-1$
return null;
@ -161,7 +181,7 @@ public class DownloadOsmandIndexesHelper {
}
@Override
public DownloadEntry createDownloadEntry(Context ctx) {
public DownloadEntry createDownloadEntry(Context ctx, DownloadActivityType type) {
return new DownloadEntry(assetName, destFile, dateModified);
}
}
@ -173,6 +193,7 @@ public class DownloadOsmandIndexesHelper {
private String fileName;
private String size;
private IndexItem attachedItem;
private DownloadActivityType type;
public IndexItem(String fileName, String description, String date, String size, String parts) {
this.fileName = fileName;
@ -180,42 +201,29 @@ public class DownloadOsmandIndexesHelper {
this.date = date;
this.size = size;
this.parts = parts;
this.type = DownloadActivityType.NORMAL_FILE;
}
public DownloadActivityType getType() {
return type;
}
public void setType(DownloadActivityType type) {
this.type = type;
}
public IndexItem getAttachedItem() {
return attachedItem;
}
public String getVisibleDescription(Context ctx){
public String getVisibleDescription(Context ctx, DownloadActivityType type){
String s = ""; //$NON-NLS-1$
if(type == DownloadActivityType.ROADS_FILE){
return ctx.getString(R.string.download_roads_only_item);
}
if (fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)
|| fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT_ZIP)) {
// Takes too much space
// String lowerCase = description.toLowerCase();
// if (lowerCase.contains("map")) { //$NON-NLS-1$
// if (s.length() > 0) {
// s += ", "; //$NON-NLS-1$
// }
// s += ctx.getString(R.string.map_index);
// }
// if (lowerCase.contains("poi")) { //$NON-NLS-1$
// if (s.length() > 0) {
// s += ", "; //$NON-NLS-1$
// }
// s += ctx.getString(R.string.poi);
// }
// if (lowerCase.contains("transport")) { //$NON-NLS-1$
// if (s.length() > 0) {
// s += ", "; //$NON-NLS-1$
// }
// s += ctx.getString(R.string.transport);
// }
// if (lowerCase.contains("address")) { //$NON-NLS-1$
// if (s.length() > 0 ) {
// s += ", "; //$NON-NLS-1$
// }
// s += ctx.getString(R.string.address);
// }
} else if (fileName.endsWith(IndexConstants.VOICE_INDEX_EXT_ZIP)) {
s = ctx.getString(R.string.voice);
} else if (fileName.endsWith(IndexConstants.TTSVOICE_INDEX_EXT_ZIP)) {
@ -264,7 +272,7 @@ public class DownloadOsmandIndexesHelper {
return parts;
}
public DownloadEntry createDownloadEntry(Context ctx) {
public DownloadEntry createDownloadEntry(Context ctx, DownloadActivityType type) {
IndexItem item = this;
String fileName = item.getFileName();
File parent = null;
@ -293,6 +301,10 @@ public class DownloadOsmandIndexesHelper {
toCheckPostfix = ""; //$NON-NLS-1$
unzipDir = true;
}
if(type == DownloadActivityType.ROADS_FILE) {
toSavePostfix = "-roads" + toSavePostfix;
toCheckPostfix = "-roads" + toCheckPostfix;
}
if(parent != null) {
parent.mkdirs();
// ".nomedia" indicates there are no pictures and no music to list in this dir for the Gallery and Music apps
@ -312,6 +324,7 @@ public class DownloadOsmandIndexesHelper {
} else {
entry = new DownloadEntry();
int ls = fileName.lastIndexOf('_');
entry.isRoadMap = type == DownloadActivityType.ROADS_FILE;
entry.baseName = fileName.substring(0, ls);
entry.fileToSave = new File(parent, entry.baseName + toSavePostfix);
entry.unzip = unzipDir;
@ -338,10 +351,25 @@ public class DownloadOsmandIndexesHelper {
}
}
if(attachedItem != null) {
entry.attachedEntry = attachedItem.createDownloadEntry(ctx);
entry.attachedEntry = attachedItem.createDownloadEntry(ctx, type);
}
return entry;
}
public String convertServerFileNameToLocal(){
String e = getFileName();
int l = e.lastIndexOf('_');
String s;
if(e.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT) || e.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT_ZIP)){
s = IndexConstants.BINARY_MAP_INDEX_EXT;
} else {
s = ""; //$NON-NLS-1$
}
if(getType() == DownloadActivityType.ROADS_FILE ) {
s = "-roads"+s;
}
return e.substring(0, l) + s;
}
}
}

View file

@ -0,0 +1,121 @@
package net.osmand.plus.download;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import net.osmand.LogUtil;
import net.osmand.Version;
import net.osmand.plus.OsmandApplication;
import net.osmand.plus.ResourceManager;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
public class DownloadTracker {
private static final Log log = LogUtil.getLog(DownloadTracker.class);
private Map<String, String> getCustomVars(Activity a) {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("App", Version.getFullVersion(a));
map.put("Device", Build.DEVICE);
map.put("Brand", Build.BRAND);
map.put("Model", Build.MODEL);
map.put("Package", a.getPackageName());
try {
PackageInfo info = a.getPackageManager().getPackageInfo(a.getPackageName(), 0);
if (info != null) {
map.put("Version name", info.versionName);
map.put("Version code", info.versionCode + "");
}
} catch (NameNotFoundException e) {
}
return map;
}
private String randomNumber() {
return (new Random(System.currentTimeMillis()).nextInt(100000000) + 100000000) + "";
}
final String beaconUrl = "http://www.google-analytics.com/__utm.gif";
final String analyticsVersion = "4.3"; // Analytics version - AnalyticsVersion
public void trackEvent(Activity a,
String category, String action, String label, int value, String trackingAcount) {
Map<String, String> parameters = new LinkedHashMap<String, String>();
try {
Map<String, String> customVariables = getCustomVars(a);
parameters.put("AnalyticsVersion", analyticsVersion);
parameters.put("utmn", randomNumber());
parameters.put("utmhn", "http://app.osmand.net");
parameters.put("utmni", "1");
parameters.put("utmt", "event");
StringBuilder customVars = new StringBuilder();
Iterator<Entry<String, String>> customs = customVariables.entrySet().iterator();
for (int i = 0; i < customVariables.size(); i++) {
Entry<String, String> n = customs.next();
if (i > 0) {
customVars.append("*");
}
// "'" => "'0", ')' => "'1", '*' => "'2", '!' => "'3",
customVars.append((i + 1) + "!").append((n.getKey() + n.getValue()));
}
parameters.put("utmcs", "UTF-8");
parameters.put("utmul", "en");
parameters.put("utmhid", (System.currentTimeMillis() / 1000) + "");
parameters.put("utmac", trackingAcount);
String domainHash = "app.osmand.net".hashCode() + "";
String utma = domainHash + ".";
File fl = ((OsmandApplication) a.getApplication()).getSettings().extendOsmandPath(ResourceManager.APP_DIR + ".nomedia");
if (fl.exists()) {
utma += (fl.lastModified()) + ".";
} else {
utma += (randomNumber()) + ".";
}
utma += ((System.currentTimeMillis() / 1000) + ".");
utma += ((System.currentTimeMillis() / 1000) + ".");
utma += ((System.currentTimeMillis() / 1000) + ".");
utma += "1";
parameters.put("utmcc", "__utma=" + utma + ";");
parameters.put("utme", MessageFormat.format("5({0}*{1}*{2})({3})", category, action, label == null ? "" : label, value)
+ customVars);
StringBuilder urlString = new StringBuilder(beaconUrl + "?");
Iterator<Entry<String, String>> it = parameters.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> e = it.next();
urlString.append(e.getKey()).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8"));
if (it.hasNext()) {
urlString.append("&");
}
}
log.debug(urlString);
URL url = new URL(urlString.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setDoInput(false);
conn.setDoOutput(false);
conn.connect();
log.info("Response analytics is " + conn.getResponseCode() + " " + conn.getResponseMessage());
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}

View file

@ -1,25 +1,27 @@
package net.osmand.plus;
package net.osmand.plus.download;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.List;
import net.osmand.data.IndexConstants;
import net.osmand.plus.DownloadOsmandIndexesHelper.IndexItem;
import net.osmand.plus.download.DownloadOsmandIndexesHelper.IndexItem;
/**
* @author Pavol Zibrita <pavol.zibrita@gmail.com>
*/
public class IndexFileList implements Serializable {
private static final long serialVersionUID = 1L;
private boolean downloadedFromInternet = false;
IndexItem basemap;
TreeMap<String, IndexItem> indexFiles = new TreeMap<String, IndexItem>(new Comparator<String>(){
ArrayList<IndexItem> indexFiles = new ArrayList<IndexItem>();
private String mapversion;
private Comparator<IndexItem> comparator = new Comparator<IndexItem>(){
@Override
public int compare(String object1, String object2) {
public int compare(IndexItem o1, IndexItem o2) {
String object1 = o1.getFileName();
String object2 = o2.getFileName();
if(object1.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
if(object2.endsWith(IndexConstants.ANYVOICE_INDEX_EXT_ZIP)){
return object1.compareTo(object2);
@ -31,12 +33,7 @@ public class IndexFileList implements Serializable {
}
return object1.compareTo(object2);
}
});
private String mapversion;
public IndexFileList() {
}
};
public void setDownloadedFromInternet(boolean downloadedFromInternet) {
this.downloadedFromInternet = downloadedFromInternet;
@ -50,20 +47,24 @@ public class IndexFileList implements Serializable {
this.mapversion = mapversion;
}
public void add(String name, IndexItem indexItem) {
public void add(IndexItem indexItem) {
if (indexItem.isAccepted()) {
indexFiles.put(name, indexItem);
indexFiles.add(indexItem);
}
if(name.toLowerCase().startsWith("world_basemap")) {
if(indexItem.getFileName().toLowerCase().startsWith("world_basemap")) {
basemap = indexItem;
}
}
public void sort(){
Collections.sort(indexFiles, comparator);
}
public boolean isAcceptable() {
return (indexFiles != null && !indexFiles.isEmpty()) || (mapversion != null);
}
public Map<String, IndexItem> getIndexFiles() {
public List<IndexItem> getIndexFiles() {
return indexFiles;
}
@ -80,4 +81,13 @@ public class IndexFileList implements Serializable {
}
return false;
}
public IndexItem getIndexFilesByName(String key) {
for(IndexItem i : indexFiles) {
if(i.getFileName().equals(key)) {
return i;
}
}
return null;
}
}

View file

@ -0,0 +1,90 @@
package net.osmand.plus.download;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import android.content.Context;
import net.osmand.plus.R;
import net.osmand.plus.download.DownloadOsmandIndexesHelper.IndexItem;
public class IndexItemCategory implements Comparable<IndexItemCategory> {
public final String name;
public final List<IndexItem> items = new ArrayList<IndexItem>();
private final int order;
public IndexItemCategory(String name, int order) {
this.name = name;
this.order = order;
}
@Override
public int compareTo(IndexItemCategory another) {
return order < another.order ? -1 : 1;
}
public static List<IndexItemCategory> categorizeIndexItems(Context ctx, Collection<IndexItem> indexItems) {
final Map<String, IndexItemCategory> cats = new TreeMap<String, IndexItemCategory>();
for (IndexItem i : indexItems) {
int nameId = R.string.index_name_other;
int order = 0;
String lc = i.getFileName().toLowerCase();
if (lc.endsWith(".voice.zip")) {
nameId = R.string.index_name_voice;
order = 1;
} else if (lc.contains(".ttsvoice.zip")) {
nameId = R.string.index_name_tts_voice;
order = 2;
} else if (lc.startsWith("us")) {
nameId = R.string.index_name_us;
order = 31;
} else if (lc.contains("_northamerica_")) {
nameId = R.string.index_name_north_america;
order = 30;
} else if (lc.contains("_centralamerica_") || lc.contains("central-america")) {
nameId = R.string.index_name_central_america;
order = 40;
} else if (lc.contains("_southamerica_") || lc.contains("south-america")) {
nameId = R.string.index_name_south_america;
order = 45;
} else if (lc.startsWith("france_")) {
nameId = R.string.index_name_france;
order = 17;
} else if (lc.startsWith("germany_")) {
nameId = R.string.index_name_germany;
order = 16;
} else if (lc.contains("_europe_")) {
nameId = R.string.index_name_europe;
order = 15;
} else if (lc.startsWith("russia_")) {
nameId = R.string.index_name_russia;
order = 18;
} else if (lc.contains("africa")) {
nameId = R.string.index_name_africa;
order = 80;
} else if (lc.contains("_asia_")) {
nameId = R.string.index_name_asia;
order = 50;
} else if (lc.contains("_oceania_") || lc.contains("australia")) {
nameId = R.string.index_name_oceania;
order = 70;
} else if (lc.contains("_wiki_")) {
nameId = R.string.index_name_wiki;
order = 10;
}
String name = ctx.getString(nameId);
if (!cats.containsKey(name)) {
cats.put(name, new IndexItemCategory(name, order));
}
cats.get(name).items.add(i);
}
ArrayList<IndexItemCategory> r = new ArrayList<IndexItemCategory>(cats.values());
Collections.sort(r);
return r;
}
}

View file

@ -33,7 +33,6 @@
if (file_exists('indexes/'.$node->getAttribute('name'))) {
echo "<tr><td>".$node->getAttribute('name')."</td><td>".$node->getAttribute('date')
."</td><td>".$node->getAttribute('size')
."</td><td>Road ".$node->getAttribute('road_date')."</td><td>Road ".$node->getAttribute('road_size')
."</td><td>".$node->getAttribute('description')
;
@ -42,6 +41,23 @@
}
?>
</table>
<h1><?php echo "Table of road indexes hosted on osmand.net"; ?></h1>
<table border="1">
<?php
$res = $xpath->query('//road_region[@local]');
if($res && $res->length > 0) {
foreach($res as $node) {
if (file_exists('road-indexes/'.$node->getAttribute('name'))) {
echo "<tr><td>".$node->getAttribute('name')."</td><td>".$node->getAttribute('date')
."</td><td>".$node->getAttribute('size')
."</td><td>".$node->getAttribute('description')
;
}
}
}
?>
</table>
<h1><?php echo "Table of indexes on googlecode"; ?></h1>
<table border="1">
<?php
@ -51,9 +67,7 @@
foreach($res as $node) {
if (!file_exists('indexes/'.$node->getAttribute('name')) || !$node->getAttribute('local')) {
echo "<tr><td>".$node->getAttribute('name')."</td><td>".$node->getAttribute('date')
."</td><td>".$node->getAttribute('size')
."</td><td>Road ".$node->getAttribute('road_date')."</td><td>Road ".$node->getAttribute('road_size')
."</td><td>".$node->getAttribute('description')
."</td><td>".$node->getAttribute('size')."</td><td>".$node->getAttribute('description')
;
}
}

View file

@ -1,21 +1,57 @@
<?php
function attachRoadIndexItem($out, $indexName) {
$filename = 'road-indexes/'.$indexName;
if (file_exists($filename)) {
$zip = new ZipArchive();
if ($zip->open($filename,ZIPARCHIVE::CHECKCONS)==TRUE) {
$description = $zip->getCommentIndex(0);
$stat = $zip->statIndex( 0 );
$date= date('d.m.Y',$stat['mtime']);
$size= number_format((filesize($filename) / (1024.0*1024.0)), 1, '.', '');
$out -> setAttribute("road_file", "yes");
$out -> setAttribute("road_date", $date);
$out -> setAttribute("road_description", $description);
$out -> setAttribute("road_size", $size);
$zip->close();
function loadIndexesFromDir($output, $outputIndexes, $dir, $elementName, $mapNodes){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$zip = new ZipArchive();
while (($file = readdir($dh)) !== false) {
$filename = $dir . $file ; //"./test112.zip";
//print("processing file:" . $filename . "\n");
if ($zip->open($filename,ZIPARCHIVE::CHECKCONS)!==TRUE) {
// echo exit("cannot open <$filename>\n");
// print($filename . " cannot open as zip\n");
continue;
}
$indexName=$file;
$description = $zip->getCommentIndex(0);
$stat = $zip->statIndex( 0 );
$date= date('d.m.Y',$stat['mtime']);
$size= number_format((filesize($filename) / (1024.0*1024.0)), 1, '.', '');
$zip->close();
if($local_file) {
echo 'Local : '.$indexName.' '.$date.' '.$size.'<br>';
}
if (isset($mapNodes[$indexName])) {
$exdate = DateTime::createFromFormat('d.m.Y', $mapNodes[$indexName]->getAttribute("date"));
$localdate = DateTime::createFromFormat('d.m.Y', $date);
if($localdate->getTimestamp() <= $exdate->getTimestamp()) {
continue;
}
if($out -> getAttribute("parts")) {
$outputIndexes->removeChild($out);
$out = $output->createElement( $elementName);
$outputIndexes->appendChild($out);
}
} else {
$out = $output->createElement( $elementName);
$outputIndexes->appendChild($out);
}
$out -> setAttribute("date", $date);
$out -> setAttribute("local", "true");
$out -> setAttribute("size", $size);
$out -> setAttribute("name", $indexName);
$out -> setAttribute("description", $description);
//$mapNodes[$indexName] = $out;
}
closedir($dh);
}
} else {
print($dir . " not a directory!\n");
}
}
@ -126,66 +162,10 @@ function updateGoogleCodeIndexes($update=false) {
}
}
/// 2. append local indexes
$local = new DomDocument();
// Open a known directory, and proceed to read its contents
$dir='indexes/';
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$zip = new ZipArchive();
while (($file = readdir($dh)) !== false) {
$filename = $dir . $file ; //"./test112.zip";
//print("processing file:" . $filename . "\n");
if ($zip->open($filename,ZIPARCHIVE::CHECKCONS)!==TRUE) {
// echo exit("cannot open <$filename>\n");
// print($filename . " cannot open as zip\n");
continue;
}
$indexName=$file;
$description = $zip->getCommentIndex(0);
$stat = $zip->statIndex( 0 );
$date= date('d.m.Y',$stat['mtime']);
$size= number_format((filesize($filename) / (1024.0*1024.0)), 1, '.', '');
$zip->close();
if($local_file) {
echo 'Local : '.$indexName.' '.$date.' '.$size.'<br>';
}
if (isset($mapNodes[$indexName])) {
$exdate = DateTime::createFromFormat('d.m.Y', $mapNodes[$indexName]->getAttribute("date"));
$localdate = DateTime::createFromFormat('d.m.Y', $date);
attachRoadIndexItem($mapNodes[$indexName], $indexName);
if($localdate->getTimestamp() <= $exdate->getTimestamp()) {
continue;
}
if($out -> getAttribute("parts")) {
$outputIndexes->removeChild($out);
$out = $output->createElement( "region" );
$outputIndexes->appendChild($out);
}
} else {
$out = $output->createElement( "region" );
$outputIndexes->appendChild($out);
}
$out -> setAttribute("date", $date);
$out -> setAttribute("local", "true");
$out -> setAttribute("size", $size);
$out -> setAttribute("name", $indexName);
$out -> setAttribute("description", $description);
attachRoadIndexItem($out, $indexName);
//$mapNodes[$indexName] = $out;
}
closedir($dh);
}
} else {
print($dir . " not a directory!\n");
}
if($local_file) {
// header('Content-Type: text/xml');
// echo $output->asXML();
}
// Open a known directory, and proceed to read its contents
loadIndexesFromDir($output, $outputIndexes, 'indexes/', 'region', $mapNodes);
loadIndexesFromDir($output, $outputIndexes, 'road-indexes/', 'road_region');
$output->save($localFileName);
}