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