Send X-Error-Format workaround on OAuth PUT too
[potlatch2.git] / net / systemeD / halcyon / connection / XMLConnection.as
1 package net.systemeD.halcyon.connection {
2
3     import flash.events.*;
4         import mx.rpc.http.HTTPService;
5         import mx.rpc.events.*;
6         import flash.system.Security;
7         import flash.net.*;
8     import org.iotashan.oauth.*;
9
10         import net.systemeD.halcyon.AttentionEvent;
11         import net.systemeD.halcyon.MapEvent;
12
13     /**
14     * XMLConnection provides all the methods required to connect to a live
15     * OSM server. See OSMConnection for connecting to a read-only .osm file
16     */
17         public class XMLConnection extends XMLBaseConnection {
18
19                 public function XMLConnection() {
20
21                         if (Connection.policyURL!='')
22                 Security.loadPolicyFile(Connection.policyURL);
23             var oauthPolicy:String = Connection.getParam("oauth_policy", "");
24             if ( oauthPolicy != "" ) {
25                 Security.loadPolicyFile(oauthPolicy);
26             }
27                 }
28                 
29                 override public function loadBbox(left:Number,right:Number,
30                                                                 top:Number,bottom:Number):void {
31             purgeIfFull(left,right,top,bottom);
32             if (isBboxLoaded(left,right,top,bottom)) return;
33
34             // enlarge bbox by 20% on each edge
35             var xmargin:Number=(right-left)/5;
36             var ymargin:Number=(top-bottom)/5;
37             left-=xmargin; right+=xmargin;
38             bottom-=ymargin; top+=ymargin;
39
40             var mapVars:URLVariables = new URLVariables();
41             mapVars.bbox= left+","+bottom+","+right+","+top;
42
43             var mapRequest:URLRequest = new URLRequest(Connection.apiBaseURL+"map");
44             mapRequest.data = mapVars;
45
46             sendLoadRequest(mapRequest);
47                 }
48
49                 override public function loadEntity(entity:Entity):void {
50                         var url:String=Connection.apiBaseURL + entity.getType() + "/" + entity.id;
51                         if (entity is Relation || entity is Way) url+="/full";
52                         sendLoadRequest(new URLRequest(url));
53                 }
54
55                 private function sendLoadRequest(request:URLRequest):void {
56                         var mapLoader:URLLoader = new URLLoader();
57                         mapLoader.addEventListener(Event.COMPLETE, loadedMap);
58                         mapLoader.addEventListener(IOErrorEvent.IO_ERROR, errorOnMapLoad);
59                         mapLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, mapLoadStatus);
60                         mapLoader.load(request);
61                         dispatchEvent(new Event(LOAD_STARTED));
62                 }
63
64         private function errorOnMapLoad(event:Event):void {
65                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't load the map" } ));
66                         dispatchEvent(new Event(LOAD_COMPLETED));
67         }
68         private function mapLoadStatus(event:HTTPStatusEvent):void {
69             trace("loading map status = "+event.status);
70         }
71
72         protected var appID:OAuthConsumer;
73         protected var authToken:OAuthToken;
74
75             override public function setAuthToken(id:Object):void {
76                 authToken = OAuthToken(id);
77             }
78
79         override public function hasAccessToken():Boolean {
80             return !(getAccessToken() == null);
81         }
82
83         override public function setAccessToken(key:String, secret:String):void {
84             if (key && secret) {
85               authToken = new OAuthToken(key, secret);
86             }
87         }
88
89         /* Get the stored access token, or try setting it up from loader params */
90         private function getAccessToken():OAuthToken {
91             if (authToken == null) {
92               var key:String = getParam("oauth_token", null);
93               var secret:String = getParam("oauth_token_secret", null);
94
95               if ( key != null && secret != null ) {
96                   authToken = new OAuthToken(key, secret);
97               }
98             }
99             return authToken;
100         }
101
102         private function getConsumer():OAuthConsumer {
103             if (appID == null) {
104               var key:String = getParam("oauth_consumer_key", null);
105               var secret:String = getParam("oauth_consumer_secret", null);
106
107               if ( key != null && secret != null ) {
108                   appID = new OAuthConsumer(key, secret);
109               }
110             }
111             return appID;
112         }
113
114         private var httpStatus:int = 0;
115         
116         private function recordStatus(event:HTTPStatusEvent):void {
117             httpStatus = event.status;
118         }
119         
120         private var lastUploadedChangesetTags:Object;
121         
122         override public function createChangeset(tags:Object):void {
123             lastUploadedChangesetTags = tags;
124             
125                 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
126                 var changeset:XML = <changeset />;
127                 for (var tagKey:Object in tags) {
128               var tagXML:XML = <tag/>;
129               tagXML.@k = tagKey;
130               tagXML.@v = tags[tagKey];
131               changesetXML.changeset.appendChild(tagXML);
132             }        
133
134                         sendOAuthPut(Connection.apiBaseURL+"changeset/create",
135                                                  changesetXML,
136                                                  changesetCreateComplete, changesetCreateError, recordStatus);
137             }
138
139         private function changesetCreateComplete(event:Event):void {
140             // response should be a Number changeset id
141             var id:Number = Number(URLLoader(event.target).data);
142             
143             // which means we now have a new changeset!
144             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
145         }
146
147         private function changesetCreateError(event:IOErrorEvent):void {
148             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
149         }
150
151                 override public function closeChangeset():void {
152             var cs:Changeset = getActiveChangeset();
153                         if (!cs) return;
154                         
155                         sendOAuthPut(Connection.apiBaseURL+"changeset/"+cs.id+"/close",
156                                                  null,
157                                                  changesetCloseComplete, changesetCloseError, recordStatus);
158                         closeActiveChangeset();
159                 }
160                 
161                 private function changesetCloseComplete(event:Event):void { 
162                         dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, "Changeset closed"));
163                 }
164                 private function changesetCloseError(event:Event):void { 
165                         dispatchEvent(new AttentionEvent(AttentionEvent.ALERT, null, "Couldn't close changeset", 1));
166                 }
167
168         private function signedOAuthURL(url:String, method:String):String {
169             // method should be PUT, GET, POST or DELETE
170             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
171             var oauthRequest:OAuthRequest = new OAuthRequest(method, url, null, getConsumer(), authToken);
172             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING);
173             return String(urlStr);
174         }
175
176                 private function sendOAuthPut(url:String, xml:XML, onComplete:Function, onError:Function, onStatus:Function):void {
177             // build the request
178             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "PUT"));
179             urlReq.method = "POST";
180                         if (xml) { urlReq.data = xml.toXMLString(); } else { urlReq.data = true; }
181             urlReq.contentType = "application/xml";
182             urlReq.requestHeaders = [ new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"), 
183                                                   new URLRequestHeader("X-Error-Format", "XML") ];
184             var loader:URLLoader = new URLLoader();
185             loader.addEventListener(Event.COMPLETE, onComplete);
186             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
187             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
188                 loader.load(urlReq);
189                 }
190
191         private function sendOAuthGet(url:String, onComplete:Function, onError:Function, onStatus:Function):void {
192             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "GET"));
193             urlReq.method = "GET";
194             var loader:URLLoader = new URLLoader();
195             loader.addEventListener(Event.COMPLETE, onComplete);
196             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
197             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
198             loader.load(urlReq);
199         }
200
201         override public function uploadChanges():void {
202             var changeset:Changeset = getActiveChangeset();
203             var upload:XML = <osmChange version="0.6"/>
204             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
205             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
206             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
207             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
208             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
209             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
210             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot, false));
211             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot, true));
212             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot, false));
213             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot, true));
214             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot, false));
215             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot, true));
216
217             // now actually upload them
218             // make an OAuth query
219             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
220
221             // build the actual request
222                         var serv:HTTPService=new HTTPService();
223                         serv.method="POST";
224                         serv.url=signedOAuthURL(url, "POST");
225                         serv.contentType = "text/xml";
226                         serv.headers={'X-Error-Format':'xml'};
227                         serv.request=" ";
228                         serv.resultFormat="e4x";
229                         serv.requestTimeout=0;
230                         serv.addEventListener(ResultEvent.RESULT, diffUploadComplete);
231                         serv.addEventListener(FaultEvent.FAULT, diffUploadIOError);
232                         serv.send(upload);
233                 
234                 dispatchEvent(new Event(SAVE_STARTED));
235         }
236
237         private function diffUploadComplete(event:ResultEvent):void {
238                         var results:XML = XML(event.result);
239
240                         // was it an error document?
241                         if (results.name().localName=='osmError') {
242                         dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
243                                 diffUploadAPIError(results.status, results.message);
244                                 return;
245                         }
246
247             // response should be XML describing the progress
248             
249             for each( var update:XML in results.child("*") ) {
250                 var oldID:Number = Number(update.@old_id);
251                 var newID:Number = Number(update.@new_id);
252                 var version:uint = uint(update.@new_version);
253                 var type:String = update.name();
254
255                                 if (newID==0) {
256                                         // delete
257                         if      (type == "node"    ) { killNode(oldID); }
258                         else if (type == "way"     ) { killWay(oldID); }
259                         else if (type == "relation") { killRelation(oldID); }
260                                         
261                                 } else {
262                                         // create/update
263                         if      (type == "node"    ) { renumberNode(oldID, newID, version); getNode(newID).markClean(); }
264                         else if (type == "way"     ) { renumberWay(oldID, newID, version); getWay(newID).markClean(); }
265                         else if (type == "relation") { renumberRelation(oldID, newID, version); getRelation(newID).markClean(); }
266                                 }
267             }
268
269             dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
270                         freshenActiveChangeset();
271             markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
272             MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
273         }
274
275                 private function diffUploadIOError(event:FaultEvent):void {
276                         trace(event.fault);
277                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+event.fault.faultString } ));
278                         dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
279                 }
280
281                 private function diffUploadAPIError(status:String, message:String):void {
282                         var matches:Array;
283                         switch (status) {
284
285                                 case '409 Conflict':
286                                         if (message.match(/changeset/i)) { throwChangesetError(message); return; }
287                                         matches=message.match(/mismatch.+had: (\d+) of (\w+) (\d+)/i);
288                                         if (matches) { throwConflictError(findEntity(matches[2],matches[3]), Number(matches[1]), message); return; }
289                                         break;
290                                 
291                                 case '410 Gone':
292                                         matches=message.match(/The (\w+) with the id (\d+)/i);
293                                         if (matches) { throwAlreadyDeletedError(findEntity(matches[1],matches[2]), message); return; }
294                                         break;
295                                 
296                                 case '412 Precondition Failed':
297                                         matches=message.match(/Node (\d+) is still used/i);
298                                         if (matches) { throwInUseError(findEntity('Node',matches[1]), message); return; }
299                                         matches=message.match(/relation (\d+) is used/i);
300                                         if (matches) { throwInUseError(findEntity('Relation',matches[1]), message); return; }
301                                         matches=message.match(/Way (\d+) still used/i);
302                                         if (matches) { throwInUseError(findEntity('Way',matches[1]), message); return; }
303                                         matches=message.match(/Cannot update (\w+) (\d+)/i);
304                                         if (matches) { throwEntityError(findEntity(matches[1],matches[2]), message); return; }
305                                         matches=message.match(/Relation with id (\d+)/i);
306                                         if (matches) { throwEntityError(findEntity('Relation',matches[1]), message); return; }
307                                         matches=message.match(/Way (\d+) requires the nodes/i);
308                                         if (matches) { throwEntityError(findEntity('Way',matches[1]), message); return; }
309                                         throwBugError(message); return;
310                                 
311                                 case '404 Not Found':
312                                         throwBugError(message); return;
313                                         
314                                 case '400 Bad Request':
315                                         matches=message.match(/Element (\w+)\/(\d+)/i);
316                                         if (matches) { throwEntityError(findEntity(matches[1],matches[2]), message); return; }
317                                         matches=message.match(/You tried to add \d+ nodes to way (\d+)/i);
318                                         if (matches) { throwEntityError(findEntity('Way',matches[1]), message); return; }
319                                         throwBugError(message); return;
320                         }
321
322                         // Not caught, so just throw a generic server error
323                         throwServerError(message);
324                 }
325
326         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
327             var create:XML = <create version="0.6"/>
328             for each( var id:Number in getIDs() ) {
329                 var entity:Entity = get(id);
330                 if ( id >= 0 || entity.deleted )
331                     continue;
332                     
333                 var xml:XML = serialise(entity);
334                 xml.@changeset = changeset.id;
335                 create.appendChild(xml);
336             }
337             return create.hasComplexContent() ? create : <!-- blank create section -->;
338         }
339
340                 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function, ifUnused:Boolean):XML {
341             var del:XML = <delete version="0.6"/>
342             if (ifUnused) del.@["if-unused"] = "true";
343             for each( var id:Number in getIDs() ) {
344                 var entity:Entity = get(id);
345                 // creates are already included
346                 if ( id < 0 || !entity.deleted || entity.parentsLoaded==ifUnused)
347                     continue;
348                     
349                 var xml:XML = serialise(entity);
350                 xml.@changeset = changeset.id;
351                 del.appendChild(xml);
352             }
353             return del.hasComplexContent() ? del : <!-- blank delete section -->;
354                 }
355
356         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
357             var modify:XML = <modify version="0.6"/>
358             for each( var id:Number in getIDs() ) {
359                 var entity:Entity = get(id);
360                 // creates and deletes are already included
361                 if ( id < 0 || entity.deleted || !entity.isDirty )
362                     continue;
363                     
364                 var xml:XML = serialise(entity);
365                 xml.@changeset = changeset.id;
366                 modify.appendChild(xml);
367             }
368             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
369         }
370
371         private function serialiseNode(node:Node):XML {
372             var xml:XML = serialiseEntityRoot(node); //<node/>
373             serialiseEntityTags(node, xml);
374             xml.@lat = node.lat;
375             xml.@lon = node.lon;
376             return xml;
377         }
378
379         private function serialiseWay(way:Way):XML {
380             var xml:XML = serialiseEntityRoot(way); //<node/>
381             serialiseEntityTags(way, xml);
382             for ( var i:uint = 0; i < way.length; i++ ) {
383                 var nd:XML = <nd/>
384                 nd.@ref = way.getNode(i).id;
385                 xml.appendChild(nd);
386             }
387             return xml;
388         }
389
390         private function serialiseRelation(relation:Relation):XML {
391             var xml:XML = serialiseEntityRoot(relation); //<node/>
392             serialiseEntityTags(relation, xml);
393             for ( var i:uint = 0; i < relation.length; i++ ) {
394                 var relMember:RelationMember = relation.getMember(i);
395                 var member:XML = <member/>
396                 member.@ref = relMember.entity.id;
397                 member.@type = relMember.entity.getType();
398                 member.@role = relMember.role;
399                 xml.appendChild(member);
400             }
401             return xml;
402         }
403         
404                 private function serialiseEntityRoot(entity:Object):XML {
405                         var xml:XML;
406                         if      (entity is Way     ) { xml = <way/> }
407                         else if (entity is Node    ) { xml = <node/> }
408                         else if (entity is Relation) { xml = <relation/> }
409                         xml.@id = entity.id;
410                         xml.@version = entity.version;
411                         return xml;
412                 }
413
414         private function serialiseEntityTags(entity:Entity, xml:XML):void {
415             xml.@id = entity.id;
416             xml.@version = entity.version;
417             for each( var tag:Tag in entity.getTagArray() ) {
418               if (tag.key == 'created_by') {
419                 entity.setTag('created_by', null, MainUndoStack.getGlobalStack().addAction);
420                 continue;
421               }
422               var tagXML:XML = <tag/>
423               tagXML.@k = tag.key;
424               tagXML.@v = tag.value;
425               xml.appendChild(tagXML);
426             }
427         }
428
429         override public function fetchUserTraces(refresh:Boolean=false):void {
430             if (traces_loaded && !refresh) {
431               dispatchEvent(new Event(TRACES_LOADED));
432             } else {
433               sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
434                           tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
435               dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
436             }
437         }
438
439         private function tracesLoadComplete(event:Event):void {
440             clearTraces();
441             var files:XML = new XML(URLLoader(event.target).data);
442             for each(var traceData:XML in files.gpx_file) {
443               var t:Trace = new Trace().fromXML(traceData);
444               addTrace(t);
445             }
446             traces_loaded = true;
447             dispatchEvent(new Event(LOAD_COMPLETED));
448             dispatchEvent(new Event(TRACES_LOADED));
449         }
450
451         override public function fetchTrace(id:Number, callback:Function):void {
452             sendOAuthGet(Connection.apiBaseURL+"gpx/"+id+"/data.xml", 
453                                 function(e:Event):void { 
454                         dispatchEvent(new Event(LOAD_COMPLETED));
455                                         callback(e);
456                                 }, errorOnMapLoad, mapLoadStatus); // needs error handlers
457             dispatchEvent(new Event(LOAD_STARTED)); //specifc to map or reusable?
458         }
459         }
460 }