1 package net.systemeD.halcyon.connection {
5 import flash.system.Security;
7 import org.iotashan.oauth.*;
9 import net.systemeD.halcyon.MapEvent;
12 * XMLConnection provides all the methods required to connect to a live
13 * OSM server. See OSMConnection for connecting to a read-only .osm file
15 public class XMLConnection extends XMLBaseConnection {
17 //public var readConnection:NetConnection;
19 public function XMLConnection() {
21 if (Connection.policyURL!='')
22 Security.loadPolicyFile(Connection.policyURL);
23 var oauthPolicy:String = Connection.getParam("oauth_policy", "");
24 if ( oauthPolicy != "" ) {
25 Security.loadPolicyFile(oauthPolicy);
29 override public function loadBbox(left:Number,right:Number,
30 top:Number,bottom:Number):void {
31 var mapVars:URLVariables = new URLVariables();
32 mapVars.bbox= left+","+bottom+","+right+","+top;
34 var mapRequest:URLRequest = new URLRequest(Connection.apiBaseURL+"map");
35 mapRequest.data = mapVars;
37 var mapLoader:URLLoader = new URLLoader();
38 mapLoader.addEventListener(Event.COMPLETE, loadedMap);
39 mapLoader.addEventListener(IOErrorEvent.IO_ERROR, errorOnMapLoad);
40 mapLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, mapLoadStatus);
41 mapLoader.load(mapRequest);
42 dispatchEvent(new Event(LOAD_STARTED));
45 private function errorOnMapLoad(event:Event):void {
46 dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't load the map" } ));
48 private function mapLoadStatus(event:HTTPStatusEvent):void {
49 trace("loading map status = "+event.status);
52 protected var appID:OAuthConsumer;
53 protected var authToken:OAuthToken;
55 override public function setAppID(id:Object):void {
56 appID = OAuthConsumer(id);
59 override public function setAuthToken(id:Object):void {
60 authToken = OAuthToken(id);
63 private var httpStatus:int = 0;
65 private function recordStatus(event:HTTPStatusEvent):void {
66 httpStatus = event.status;
69 private var lastUploadedChangesetTags:Object;
71 override public function createChangeset(tags:Object):void {
72 lastUploadedChangesetTags = tags;
74 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
75 var changeset:XML = <changeset />;
76 for (var tagKey:Object in tags) {
77 var tagXML:XML = <tag/>;
79 tagXML.@v = tags[tagKey];
80 changesetXML.changeset.appendChild(tagXML);
83 sendOAuthPut(Connection.apiBaseURL+"changeset/create",
85 changesetCreateComplete, changesetCreateError, recordStatus);
88 private function changesetCreateComplete(event:Event):void {
89 // response should be a Number changeset id
90 var id:Number = Number(URLLoader(event.target).data);
92 // which means we now have a new changeset!
93 setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
96 private function changesetCreateError(event:IOErrorEvent):void {
97 dispatchEvent(new Event(NEW_CHANGESET_ERROR));
100 override public function closeChangeset():void {
101 var cs:Changeset = getActiveChangeset();
104 sendOAuthPut(Connection.apiBaseURL+"changeset/"+cs.id+"/close",
106 changesetCloseComplete, changesetCloseError, recordStatus);
107 closeActiveChangeset();
110 private function changesetCloseComplete(event:Event):void { }
111 private function changesetCloseError(event:Event):void { }
112 // ** TODO: when we get little floating warnings, we can send a happy or sad one up
114 private function signedOAuthURL(url:String, method:String):String {
115 // method should be PUT, GET, POST or DELETE
116 var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
117 var oauthRequest:OAuthRequest = new OAuthRequest(method, url, null, appID, authToken);
118 var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING);
119 return String(urlStr);
122 private function sendOAuthPut(url:String, xml:XML, onComplete:Function, onError:Function, onStatus:Function):void {
124 var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "PUT"));
125 urlReq.method = "POST";
126 if (xml) { urlReq.data = xml.toXMLString(); } else { urlReq.data = true; }
127 urlReq.contentType = "application/xml";
128 urlReq.requestHeaders = new Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
129 var loader:URLLoader = new URLLoader();
130 loader.addEventListener(Event.COMPLETE, onComplete);
131 loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
132 loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
136 private function sendOAuthGet(url:String, onComplete:Function, onError:Function, onStatus:Function):void {
137 var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "GET"));
138 urlReq.method = "GET";
139 var loader:URLLoader = new URLLoader();
140 loader.addEventListener(Event.COMPLETE, onComplete);
141 loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
142 loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
146 override public function uploadChanges():void {
147 var changeset:Changeset = getActiveChangeset();
148 var upload:XML = <osmChange version="0.6"/>
149 upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
150 upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
151 upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
152 upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
153 upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
154 upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
155 upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot));
156 upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot));
157 upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot));
159 // now actually upload them
160 // make an OAuth query
162 var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
164 // build the actual request
165 var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "POST"));
166 urlReq.method = "POST";
167 urlReq.data = upload.toXMLString();
168 urlReq.contentType = "text/xml";
169 var loader:URLLoader = new URLLoader();
170 loader.addEventListener(Event.COMPLETE, diffUploadComplete);
171 loader.addEventListener(IOErrorEvent.IO_ERROR, diffUploadError);
172 loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
175 dispatchEvent(new Event(SAVE_STARTED));
178 private function diffUploadComplete(event:Event):void {
179 // response should be XML describing the progress
180 var results:XML = new XML((URLLoader(event.target).data));
182 for each( var update:XML in results.child("*") ) {
183 var oldID:Number = Number(update.@old_id);
184 var newID:Number = Number(update.@new_id);
185 var version:uint = uint(update.@new_version);
186 var type:String = update.name();
190 if ( type == "node" ) killNode(oldID);
191 else if ( type == "way" ) killWay(oldID);
192 else if ( type == "relation" ) killRelation(oldID);
197 if ( type == "node" ) entity = getNode(oldID);
198 else if ( type == "way" ) entity = getWay(oldID);
199 else if ( type == "relation" ) entity = getRelation(oldID);
200 entity.markClean(newID, version);
202 if ( oldID != newID ) {
203 if ( type == "node" ) renumberNode(oldID, entity as Node, false);
204 else if ( type == "way" ) renumberWay(oldID, entity as Way, false);
205 else if ( type == "relation" ) renumberRelation(oldID, entity as Relation, false);
210 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
211 freshenActiveChangeset();
212 markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
213 MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
216 private function diffUploadError(event:IOErrorEvent):void {
217 dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+httpStatus+" "+event.text } ));
218 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
221 private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
222 var create:XML = <create version="0.6"/>
223 for each( var id:Number in getIDs() ) {
224 var entity:Entity = get(id);
225 if ( id >= 0 || entity.deleted )
228 var xml:XML = serialise(entity);
229 xml.@changeset = changeset.id;
230 create.appendChild(xml);
232 return create.hasComplexContent() ? create : <!-- blank create section -->;
235 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
236 var del:XML = <delete version="0.6"/>
237 for each( var id:Number in getIDs() ) {
238 var entity:Entity = get(id);
239 // creates are already included
240 if ( id < 0 || !entity.deleted )
243 var xml:XML = serialise(entity);
244 xml.@changeset = changeset.id;
245 del.appendChild(xml);
247 return del.hasComplexContent() ? del : <!-- blank delete section -->;
250 private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
251 var modify:XML = <modify version="0.6"/>
252 for each( var id:Number in getIDs() ) {
253 var entity:Entity = get(id);
254 // creates and deletes are already included
255 if ( id < 0 || entity.deleted || !entity.isDirty )
258 var xml:XML = serialise(entity);
259 xml.@changeset = changeset.id;
260 modify.appendChild(xml);
262 return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
265 private function serialiseNode(node:Node):XML {
266 var xml:XML = serialiseEntityRoot(node); //<node/>
267 serialiseEntityTags(node, xml);
273 private function serialiseWay(way:Way):XML {
274 var xml:XML = serialiseEntityRoot(way); //<node/>
275 serialiseEntityTags(way, xml);
276 for ( var i:uint = 0; i < way.length; i++ ) {
278 nd.@ref = way.getNode(i).id;
284 private function serialiseRelation(relation:Relation):XML {
285 var xml:XML = serialiseEntityRoot(relation); //<node/>
286 serialiseEntityTags(relation, xml);
287 for ( var i:uint = 0; i < relation.length; i++ ) {
288 var relMember:RelationMember = relation.getMember(i);
289 var member:XML = <member/>
290 member.@ref = relMember.entity.id;
291 member.@type = relMember.entity.getType();
292 member.@role = relMember.role;
293 xml.appendChild(member);
298 private function serialiseEntityRoot(entity:Object):XML {
300 if (entity is Way ) { xml = <way/> }
301 else if (entity is Node ) { xml = <node/> }
302 else if (entity is Relation) { xml = <relation/> }
304 xml.@version = entity.version;
308 private function serialiseEntityTags(entity:Entity, xml:XML):void {
310 xml.@version = entity.version;
311 for each( var tag:Tag in entity.getTagArray() ) {
312 if (tag.key == 'created_by') {
313 entity.setTag('created_by', null, MainUndoStack.getGlobalStack().addAction);
316 var tagXML:XML = <tag/>
318 tagXML.@v = tag.value;
319 xml.appendChild(tagXML);
323 override public function fetchUserTraces(refresh:Boolean=false):void {
324 if (traces_loaded && !refresh) {
325 dispatchEvent(new Event(TRACES_LOADED));
327 sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
328 tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
329 dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
333 private function tracesLoadComplete(event:Event):void {
335 var files:XML = new XML(URLLoader(event.target).data);
336 for each(var traceData:XML in files.gpx_file) {
337 var t:Trace = new Trace().fromXML(traceData);
340 traces_loaded = true;
341 dispatchEvent(new Event(LOAD_COMPLETED));
342 dispatchEvent(new Event(TRACES_LOADED));
345 override public function fetchTrace(id:Number, callback:Function):void {
346 sendOAuthGet(Connection.apiBaseURL+"gpx/"+id+"/data.xml", callback, errorOnMapLoad, mapLoadStatus); // needs error handlers
347 dispatchEvent(new Event(LOAD_STARTED)); //specifc to map or reusable?