Implement share GPX files functionality

This commit is contained in:
Victor Shcherb 2011-08-28 20:32:25 +02:00
parent e626425209
commit 0cb0263259
8 changed files with 223 additions and 17 deletions

View file

@ -1,10 +1,19 @@
package net.osmand;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.zip.GZIPOutputStream;
import net.osmand.LogUtil;
@ -211,4 +220,83 @@ public class Algoritms {
}
return false;
}
private static final String BOUNDARY = "CowMooCowMooCowCowCow"; //$NON-NLS-1$
public static String uploadFile(String urlText, File fileToUpload, String formName, boolean gzip){
URL url;
try {
log.info("Start uploading file to " + urlText + " " +fileToUpload.getName());
url = new URL(urlText);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); //$NON-NLS-1$ //$NON-NLS-2$
conn.setRequestProperty("User-Agent", "Osmand"); //$NON-NLS-1$ //$NON-NLS-2$
OutputStream ous = conn.getOutputStream();
ous.write(("--" + BOUNDARY+"\r\n").getBytes());
ous.write(("content-disposition: form-data; name=\""+formName+"\"; filename=\"" + fileToUpload.getName() + "\"\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$
ous.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); //$NON-NLS-1$
InputStream fis = new FileInputStream(fileToUpload);
BufferedInputStream bis = new BufferedInputStream(fis, 20 * 1024);
ous.flush();
if(gzip){
GZIPOutputStream gous = new GZIPOutputStream(ous, 1024);
Algoritms.streamCopy(bis, gous);
gous.flush();
gous.finish();
} else {
Algoritms.streamCopy(bis, ous);
}
ous.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); //$NON-NLS-1$ //$NON-NLS-2$
ous.flush();
Algoritms.closeStream(bis);
Algoritms.closeStream(ous);
log.info("Finish uploading file " + fileToUpload.getName());
log.info("Response code and message : " + conn.getResponseCode() + " " + conn.getResponseMessage());
if(conn.getResponseCode() != 200){
return conn.getResponseMessage();
}
InputStream is = conn.getInputStream();
StringBuilder responseBody = new StringBuilder();
if (is != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); //$NON-NLS-1$
String s;
boolean first = true;
while ((s = in.readLine()) != null) {
if(first){
first = false;
} else {
responseBody.append("\n"); //$NON-NLS-1$
}
responseBody.append(s);
}
is.close();
}
String response = responseBody.toString();
log.info("Response : " + response);
if(response.startsWith("OK")){
return null;
}
return response;
} catch (IOException e) {
log.error(e.getMessage(), e);
return e.getMessage();
}
}
private final static String URL_TO_UPLOAD_GPX = "http://download.osmand.net/upload_gpx.php";
public static void main(String[] args) throws UnsupportedEncodingException {
File file = new File("/home/victor/projects/OsmAnd/git/config/site/welcome.msg");
String url = URL_TO_UPLOAD_GPX + "?author=" + URLEncoder.encode("222", "UTF-8") + "&wd="
+ URLEncoder.encode("222", "UTF-8") + "&file="
+ URLEncoder.encode(file.getName(), "UTF-8");
Algoritms.uploadFile(url, file, "filename", true);
}
}

View file

@ -3,7 +3,10 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:id="@+id/DescriptionTextTop" android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="" android:layout_marginLeft = "3dp" android:layout_marginRight = "3dp"
android:visibility="gone"/>
<LinearLayout android:id="@+id/LoadingPanel" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp">
<Button android:id="@+id/DownloadButton" android:layout_width="wrap_content" android:layout_gravity="right" android:layout_height="wrap_content" android:text="@string/local_index_download"
android:layout_marginLeft = "3dp" android:layout_marginTop ="3dp" android:layout_marginRight = "3dp"/>
@ -19,7 +22,7 @@
<ProgressBar android:id="@+id/ProgressBar" android:layout_marginLeft="5dp" android:indeterminate="true" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginRight="5dp"/>
</LinearLayout>
<ExpandableListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="wrap_content"
android:layout_marginLeft="3dp" android:layout_marginTop="3dp" android:layout_marginRight="3dp" ></ExpandableListView>

View file

@ -11,14 +11,14 @@
<string name="local_index_items_restored">%1$d из %2$d объектов успешно восстановлены.</string>
<string name="local_index_no_items_to_do">Нет объектов, чтобы %1$s</string>
<string name="local_index_action_do">Вы собириаетесь %1$s %2$s объектов. Вы уверены?</string>
<string name="local_index_descr_title">Offline Data Manager:</string>
<string name="local_index_descr_title">Менеджер офлайн данных:</string>
<string name="local_index_description">Офлайн данные доступные на SD карточке. Вы можете загрузить новые, архивировать и удалить данные.</string>
<string name="local_index_mi_restore">Восстановить</string>
<string name="local_index_mi_backup">Архивировать</string>
<string name="local_index_mi_backup">Архив</string>
<string name="local_index_mi_delete">Удалить</string>
<string name="local_index_mi_reload">Обновить данные</string>
<string name="local_index_mi_reload">Обновить</string>
<string name="local_index_download">Загрузить</string>
<string name="local_index_tile_data">Тайловые данные : %1$s \nMinimum zoom : %2$d\nMaximum zoom : %3$d\nDownloadable : %4$s \nZooms downloaded : %5$s</string>
<string name="local_index_tile_data">Тайловые данные : %1$s \nМинимальный уровень : %2$d\nМаксимальный уровень : %3$d\nЗагружаемый : %4$s \nУровни загружены : %5$s</string>
<string name="local_index_poi_data">POI</string>
<string name="local_index_address_data">Адрес</string>
<string name="local_index_transport_data">Транспорт</string>

View file

@ -1,5 +1,9 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<resources>
<string name="local_index_upload_gpx_description">Upload GPX files to OSM community. They will be used to improve maps.</string>
<string name="local_index_items_uploaded">%1$d of %2$d item(s) successfully uploaded.</string>
<string name="local_index_mi_upload_gpx">Contribute to OSM...</string>
<string name="show_more_map_detail">Show more map detail</string>
<string name="show_more_map_detail_descr">Show some vector map detail (roads etc.) at lower zooms already</string>
@ -28,8 +32,8 @@
<string name="local_index_mi_restore">Restore...</string>
<string name="local_index_mi_backup">Backup...</string>
<string name="local_index_mi_delete">Delete...</string>
<string name="local_index_mi_reload">Re-initialize</string>
<string name="local_index_download">Download...</string>
<string name="local_index_mi_reload">Re-initialize...</string>
<string name="local_index_download">Download</string>
<string name="local_index_tile_data">Tile data: %1$s \nMinimum zoom : %2$d\nMaximum zoom : %3$d\nDownloadable : %4$s \nZooms downloaded : %5$s</string>
<string name="local_index_poi_data">POI data</string>
<string name="local_index_address_data">Address data</string>

View file

@ -179,7 +179,7 @@ public class GPXUtilities {
SimpleDateFormat format = new SimpleDateFormat(GPX_TIME_FORMAT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
boolean cloudMade = false;
res.cloudMadeFile = false;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new FileInputStream(f), "UTF-8"); //$NON-NLS-1$
@ -189,12 +189,12 @@ public class GPXUtilities {
while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) {
if (tok == XmlPullParser.START_TAG) {
if (parser.getName().equals("copyright")) { //$NON-NLS-1$
cloudMade |= "cloudmade".equalsIgnoreCase(parser.getAttributeValue("", "author")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
res.cloudMadeFile |= "cloudmade".equalsIgnoreCase(parser.getAttributeValue("", "author")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
} else if (parser.getName().equals("trkseg")) { //$NON-NLS-1$
res.locations.add(new ArrayList<Location>());
} else if (parser.getName().equals("wpt") || parser.getName().equals("trkpt") || //$NON-NLS-1$//$NON-NLS-2$
(!cloudMade && parser.getName().equals("rtept"))) { //$NON-NLS-1$
(!res.cloudMadeFile && parser.getName().equals("rtept"))) { //$NON-NLS-1$
// currently not distinguish different point represents all as a line
try {
currentName = ""; //$NON-NLS-1$
@ -241,9 +241,9 @@ public class GPXUtilities {
} else if (tok == XmlPullParser.END_TAG) {
if (parser.getName().equals("wpt") || //$NON-NLS-1$
parser.getName().equals("trkpt") || (!cloudMade && parser.getName().equals("rtept"))) { //$NON-NLS-1$ //$NON-NLS-2$
parser.getName().equals("trkpt") || (!res.cloudMadeFile && parser.getName().equals("rtept"))) { //$NON-NLS-1$ //$NON-NLS-2$
if (current != null) {
if (parser.getName().equals("wpt") && !cloudMade) { //$NON-NLS-1$
if (parser.getName().equals("wpt") && !res.cloudMadeFile) { //$NON-NLS-1$
res.wayPoints.add(convertLocationToWayPoint(current, currentName));
} else {
if (res.locations.isEmpty()) {

View file

@ -407,7 +407,6 @@ public class EditingPOIActivity {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 15000);
DefaultHttpClient httpclient = new DefaultHttpClient(params);
if (doAuthenticate) {
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(OsmandSettings.getOsmandSettings(ctx).USER_NAME.get() + ":" //$NON-NLS-1$
+ OsmandSettings.getOsmandSettings(ctx).USER_PASSWORD.get());

View file

@ -1,6 +1,8 @@
package net.osmand.plus.activities;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@ -47,10 +49,12 @@ import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
public class LocalIndexesActivity extends ExpandableListActivity {
private final static String URL_TO_UPLOAD_GPX = "http://download.osmand.net/upload_gpx.php";
private LoadLocalIndexTask asyncLoader;
private LocalIndexesAdapter listAdapter;
private LoadLocalIndexDescriptionTask descriptionLoader;
private LocalIndexOperationTask operationTask;
private AsyncTask<LocalIndexInfo, ?, ?> operationTask;
private boolean selectionMode = false;
private Set<LocalIndexInfo> selectedItems = new LinkedHashSet<LocalIndexInfo>();
@ -236,6 +240,7 @@ public class LocalIndexesActivity extends ExpandableListActivity {
} else if(operation == RESTORE_OPERATION){
return getString(R.string.local_index_items_restored, count, total);
}
return "";
}
@ -267,6 +272,72 @@ public class LocalIndexesActivity extends ExpandableListActivity {
reloadIndexes();
}
}
public class UploadGPXFilesTask extends AsyncTask<LocalIndexInfo, String, String> {
private OsmandSettings settings;
public UploadGPXFilesTask(){
settings = ((OsmandApplication) getApplication()).getSettings();
}
@Override
protected String doInBackground(LocalIndexInfo... params) {
int count = 0;
int total = 0;
for (LocalIndexInfo info : params) {
if (!isCancelled()) {
String warning = null;
try {
File file = new File(info.getPathToData());
String userName = settings.USER_NAME.get();
String pwd = settings.USER_PASSWORD.get();
String url = URL_TO_UPLOAD_GPX + "?author=" + URLEncoder.encode(userName, "UTF-8") + "&wd="
+ URLEncoder.encode(pwd, "UTF-8") + "&file="
+ URLEncoder.encode(file.getName(), "UTF-8");
warning = Algoritms.uploadFile(url, file, "filename", true);
} catch (UnsupportedEncodingException e) {
warning = e.getMessage();
}
total++;
if (warning == null) {
count++;
} else {
publishProgress(warning);
}
}
}
return getString(R.string.local_index_items_uploaded, count, total);
}
@Override
protected void onProgressUpdate(String... values) {
if (values.length > 0) {
StringBuilder b = new StringBuilder();
for (int i=0; i<values.length; i++) {
if(i > 0){
b.append("\n");
}
b.append(values[i]);
}
Toast.makeText(LocalIndexesActivity.this, b.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPreExecute() {
findViewById(R.id.ProgressBar).setVisibility(View.VISIBLE);
}
@Override
protected void onPostExecute(String result) {
findViewById(R.id.ProgressBar).setVisibility(View.GONE);
Toast.makeText(LocalIndexesActivity.this, result, Toast.LENGTH_LONG).show();
}
}
@ -313,6 +384,8 @@ public class LocalIndexesActivity extends ExpandableListActivity {
}
@Override
protected void onPause() {
super.onPause();
@ -343,6 +416,7 @@ public class LocalIndexesActivity extends ExpandableListActivity {
menu.add(0, R.string.local_index_mi_restore, 1, R.string.local_index_mi_restore);
menu.add(0, R.string.local_index_mi_delete, 2, R.string.local_index_mi_delete);
menu.add(0, R.string.local_index_mi_reload, 3, R.string.local_index_mi_reload);
menu.add(0, R.string.local_index_mi_upload_gpx, 4, R.string.local_index_mi_upload_gpx);
return true;
}
@ -363,6 +437,8 @@ public class LocalIndexesActivity extends ExpandableListActivity {
operationTask = new LocalIndexOperationTask(DELETE_OPERATION);
} else if(actionResId == R.string.local_index_mi_restore){
operationTask = new LocalIndexOperationTask(RESTORE_OPERATION);
} else if(actionResId == R.string.local_index_mi_upload_gpx){
operationTask = new UploadGPXFilesTask();
} else {
operationTask = null;
}
@ -380,7 +456,11 @@ public class LocalIndexesActivity extends ExpandableListActivity {
}
private void openSelectionMode(final int actionResId){
final String actionButton = getString(actionResId);
String value = getString(actionResId);
if (value.endsWith("...")) {
value = value.substring(0, value.length() - 3);
}
final String actionButton = value;
if(listAdapter.getGroupCount() == 0){
listAdapter.cancelFilter();
Toast.makeText(LocalIndexesActivity.this, getString(R.string.local_index_no_items_to_do, actionButton.toLowerCase()), Toast.LENGTH_SHORT).show();
@ -425,9 +505,13 @@ public class LocalIndexesActivity extends ExpandableListActivity {
}
});
findViewById(R.id.DownloadButton).setVisibility(View.GONE);
findViewById(R.id.DescriptionText).setVisibility(View.GONE);
findViewById(R.id.FillLayoutStart).setVisibility(View.VISIBLE);
findViewById(R.id.FillLayoutEnd).setVisibility(View.VISIBLE);
findViewById(R.id.DescriptionText).setVisibility(View.GONE);
if(R.string.local_index_mi_upload_gpx == actionResId){
((TextView) findViewById(R.id.DescriptionTextTop)).setText(R.string.local_index_upload_gpx_description);
((TextView) findViewById(R.id.DescriptionTextTop)).setVisibility(View.VISIBLE);
}
listAdapter.notifyDataSetChanged();
}
@ -439,6 +523,8 @@ public class LocalIndexesActivity extends ExpandableListActivity {
findViewById(R.id.FillLayoutEnd).setVisibility(View.GONE);
findViewById(R.id.CancelButton).setVisibility(View.GONE);
findViewById(R.id.ActionButton).setVisibility(View.GONE);
((TextView) findViewById(R.id.DescriptionTextTop)).setVisibility(View.GONE);
((TextView) findViewById(R.id.DescriptionText)).setText(R.string.local_index_description);
listAdapter.cancelFilter();
collapseAllGroups();
listAdapter.notifyDataSetChanged();
@ -457,6 +543,9 @@ public class LocalIndexesActivity extends ExpandableListActivity {
} else if(item.getItemId() == R.string.local_index_mi_restore){
listAdapter.filterCategories(true);
openSelectionMode(R.string.local_index_mi_restore);
} else if(item.getItemId() == R.string.local_index_mi_upload_gpx){
listAdapter.filterCategories(LocalIndexType.GPX_DATA);
openSelectionMode(R.string.local_index_mi_upload_gpx);
} else {
return super.onOptionsItemSelected(item);
}

23
config/site/upload_gpx.php Executable file
View file

@ -0,0 +1,23 @@
<?php
if(!isset($_GET['file']) || !isset($_GET['author']) || !isset($_GET['wd']) ) {
header('HTTP/1.0 404 Not Found');
print 'Specify file, author name and password';
die(1);
}
$target_path = '/var/www/gpx/';
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
$target_file = tempnam($target_path, $_GET['author'] . '.' . basename($_FILES['filename']['name']). '.') ;
if(move_uploaded_file($_FILES['filename']['tmp_name'], $target_file)) {
header('HTTP/1.1 200 Ok');
echo "OK. Upload successfull.";
} else {
echo "There was an error uploading the file, please try again!";
}
} else {
echo "Error : file is not uploaded";
}
?>