-
-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathOpenStreetMapUpload.java
More file actions
224 lines (199 loc) · 7.69 KB
/
Copy pathOpenStreetMapUpload.java
File metadata and controls
224 lines (199 loc) · 7.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package net.osmtracker.activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import net.openid.appauth.AuthorizationException;
import net.openid.appauth.AuthorizationRequest;
import net.openid.appauth.AuthorizationResponse;
import net.openid.appauth.AuthorizationService;
import net.openid.appauth.AuthorizationServiceConfiguration;
import net.openid.appauth.ResponseTypeValues;
import net.openid.appauth.TokenResponse;
import net.osmtracker.OSMTracker;
import net.osmtracker.R;
import net.osmtracker.db.DataHelper;
import net.osmtracker.db.TrackContentProvider;
import net.osmtracker.db.model.Track;
import net.osmtracker.gpx.ExportToTempFileTask;
import net.osmtracker.gpx.ZipHelper;
import net.osmtracker.osm.OpenStreetMapConstants;
import net.osmtracker.osm.UploadToOpenStreetMapTask;
import java.io.File;
/**
* <p>Uploads a track on OSM using the API and
* OAuth authentication.</p>
*
* <p>This activity may be called twice during a single
* upload cycle: First to start the upload, then a second
* time when the user has authenticated using the browser.</p>
*
* @author Nicolas Guillaumin
*/
public class OpenStreetMapUpload extends TrackDetailEditor {
private static final String TAG = OpenStreetMapUpload.class.getSimpleName();
/** URL that the browser will call once the user is authenticated */
public final static String OAUTH2_CALLBACK_URL = "osmtracker://osm-upload/oath2-completed/?"+ TrackContentProvider.Schema.COL_TRACK_ID+"=";
public final static int RC_AUTH = 7;
private AuthorizationService authService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.osm_upload, getTrackId());
fieldsMandatory = true;
final Button btnOk = (Button) findViewById(R.id.osm_upload_btn_ok);
btnOk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (save()) {
startUpload();
}
}
});
final Button btnCancel = (Button) findViewById(R.id.osm_upload_btn_cancel);
btnCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// Do not show soft keyboard by default
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
/**
* Gets the track ID we were called with, either from the
* intent extras if we were started by OSMTracker, or in the
* URI if we are returning from the browser.
* @return
*/
private long getTrackId() {
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(TrackContentProvider.Schema.COL_TRACK_ID)) {
return getIntent().getExtras().getLong(TrackContentProvider.Schema.COL_TRACK_ID);
} else if (getIntent().getData().toString().startsWith(OAUTH2_CALLBACK_URL)) {
return Long.parseLong(getIntent().getData().getQueryParameter(TrackContentProvider.Schema.COL_TRACK_ID));
} else {
throw new IllegalArgumentException("Missing Track ID");
}
}
/**
* Will be called as well when we come back from the browser
* after user authentication.
*/
@Override
protected void onResume() {
super.onResume();
Cursor cursor = managedQuery(
ContentUris.withAppendedId(TrackContentProvider.CONTENT_URI_TRACK, trackId),
null, null, null, null);
if (! cursor.moveToFirst()) {
// This shouldn't occur, it's here just in case.
// So, don't make each language translate/localize it.
Toast.makeText(this, "Track ID not found.", Toast.LENGTH_SHORT).show();
finish();
return; // <--- Early return ---
}
bindTrack(Track.build(trackId, cursor, getContentResolver(), false));
}
/**
* Either starts uploading directly if we are authenticated against OpenStreetMap,
* or ask the user to authenticate via the browser.
*/
private void startUpload() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if ( prefs.contains(OSMTracker.Preferences.KEY_OSM_OAUTH2_ACCESSTOKEN) ) {
// Re-use saved token
uploadToOsm(prefs.getString(OSMTracker.Preferences.KEY_OSM_OAUTH2_ACCESSTOKEN, ""));
} else {
// Open browser and request token
requestOsmAuth();
}
}
/*
* Init Authorization request workflow.
*/
public void requestOsmAuth() {
// Authorization service configuration
AuthorizationServiceConfiguration serviceConfig =
new AuthorizationServiceConfiguration(
Uri.parse(OpenStreetMapConstants.OAuth2.Urls.AUTHORIZATION_ENDPOINT),
Uri.parse(OpenStreetMapConstants.OAuth2.Urls.TOKEN_ENDPOINT));
// Obtaining an authorization code
Uri redirectURI = Uri.parse(OAUTH2_CALLBACK_URL+trackId);
AuthorizationRequest.Builder authRequestBuilder =
new AuthorizationRequest.Builder(
serviceConfig, OpenStreetMapConstants.OAuth2.CLIENT_ID,
ResponseTypeValues.CODE, redirectURI);
AuthorizationRequest authRequest = authRequestBuilder
.setScope(OpenStreetMapConstants.OAuth2.SCOPE)
.build();
// Start activity.
authService = new AuthorizationService(this);
Intent authIntent = authService.getAuthorizationRequestIntent(authRequest);
startActivityForResult(authIntent, RC_AUTH); //when done onActivityResult will be called.
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// User is returning from authentication
if (requestCode == RC_AUTH) {
// Handling the authorization response
AuthorizationResponse resp = AuthorizationResponse.fromIntent(data);
AuthorizationException ex = AuthorizationException.fromIntent(data);
// ... process the response or exception ...
if (ex != null) {
Log.e(TAG, "Authorization Error. Exception received from server.");
Log.e(TAG, ex.getMessage());
} else if (resp == null) {
Log.e(TAG, "Authorization Error. Null response from server.");
} else {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Exchanging the authorization code
authService.performTokenRequest(
resp.createTokenExchangeRequest(),
new AuthorizationService.TokenResponseCallback() {
@Override public void onTokenRequestCompleted(
TokenResponse resp, AuthorizationException ex) {
if (resp != null) {
// exchange succeeded
SharedPreferences.Editor editor = prefs.edit();
editor.putString(OSMTracker.Preferences.KEY_OSM_OAUTH2_ACCESSTOKEN, resp.accessToken);
editor.apply();
//continue with the track Upload.
uploadToOsm(resp.accessToken);
} else {
// authorization failed, check ex for more details
Log.e(TAG, "OAuth failed.");
}
}
});
}
} else {
Log.e(TAG, "Unexpected requestCode:" + requestCode + ".");
}
}
/**
* Exports track on disk then upload to OSM.
*/
public void uploadToOsm(String accessToken) {
new ExportToTempFileTask(this, trackId) {
@Override
protected void executionCompleted() {
File fileZip = ZipHelper.zipGPXFile(context,trackId, getTmpFile());
String filename = getFilename().substring(0, getFilename().length() - 4) + DataHelper.EXTENSION_ZIP;
new UploadToOpenStreetMapTask(OpenStreetMapUpload.this, accessToken,
trackId, fileZip, filename,
etDescription.getText().toString(), etTags.getText().toString(),
Track.OSMVisibility.fromPosition(
OpenStreetMapUpload.this.spVisibility.getSelectedItemPosition())
).execute();
}
}.execute();
}
}