Merge branch 'master' into icons2
[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 Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
183             var loader:URLLoader = new URLLoader();
184             loader.addEventListener(Event.COMPLETE, onComplete);
185             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
186             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
187                 loader.load(urlReq);
188                 }
189
190         private function sendOAuthGet(url:String, onComplete:Function, onError:Function, onStatus:Function):void {
191             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "GET"));
192             urlReq.method = "GET";
193             var loader:URLLoader = new URLLoader();
194             loader.addEventListener(Event.COMPLETE, onComplete);
195             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
196             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
197             loader.load(urlReq);
198         }
199
200         override public function uploadChanges():void {
201             var changeset:Changeset = getActiveChangeset();
202             var upload:XML = <osmChange version="0.6"/>
203             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
204             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
205             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
206             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
207             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
208             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
209             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot, false));
210             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot, true));
211             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot, false));
212             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot, true));
213             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot, false));
214             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot, true));
215
216             // now actually upload them
217             // make an OAuth query
218             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
219
220             // build the actual request
221                         var serv:HTTPService=new HTTPService();
222                         serv.method="POST";
223                         serv.url=signedOAuthURL(url, "POST");
224                         serv.contentType = "text/xml";
225                         serv.headers={'X-Error-Format':'xml'};
226                         serv.request=" ";
227                         serv.resultFormat="e4x";
228                         serv.requestTimeout=0;
229                         serv.addEventListener(ResultEvent.RESULT, diffUploadComplete);
230                         serv.addEventListener(FaultEvent.FAULT, diffUploadIOError);
231                         serv.send(upload);
232                 
233                 dispatchEvent(new Event(SAVE_STARTED));
234         }
235
236         private function diffUploadComplete(event:ResultEvent):void {
237                         var results:XML = XML(event.result);
238
239                         // was it an error document?
240                         if (results.name().localName=='osmError') {
241                         dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
242                                 diffUploadAPIError(results.status, results.message);
243                                 return;
244                         }
245
246             // response should be XML describing the progress
247             
248             for each( var update:XML in results.child("*") ) {
249                 var oldID:Number = Number(update.@old_id);
250                 var newID:Number = Number(update.@new_id);
251                 var version:uint = uint(update.@new_version);
252                 var type:String = update.name();
253
254                                 if (newID==0) {
255                                         // delete
256                         if      (type == "node"    ) { killNode(oldID); }
257                         else if (type == "way"     ) { killWay(oldID); }
258                         else if (type == "relation") { killRelation(oldID); }
259                                         
260                                 } else {
261                                         // create/update
262                         if      (type == "node"    ) { renumberNode(oldID, newID, version); getNode(newID).markClean(); }
263                         else if (type == "way"     ) { renumberWay(oldID, newID, version); getWay(newID).markClean(); }
264                         else if (type == "relation") { renumberRelation(oldID, newID, version); getRelation(newID).markClean(); }
265                                 }
266             }
267
268             dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
269                         freshenActiveChangeset();
270             markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
271             MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
272         }
273
274                 private function diffUploadIOError(event:FaultEvent):void {
275                         trace(event.fault);
276                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+event.fault.faultString } ));
277                         dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
278                 }
279
280                 private function diffUploadAPIError(status:String, message:String):void {
281                         var matches:Array;
282                         switch (status) {
283
284                                 case '409 Conflict':
285                                         if (message.match(/changeset/i)) { throwChangesetError(message); return; }
286                                         matches=message.match(/mismatch.+had: (\d+) of (\w+) (\d+)/i);
287                                         if (matches) { throwConflictError(findEntity(matches[2],matches[3]), Number(matches[1]), message); return; }
288                                         break;
289                                 
290                                 case '410 Gone':
291                                         matches=message.match(/The (\w+) with the id (\d+)/i);
292                                         if (matches) { throwAlreadyDeletedError(findEntity(matches[1],matches[2]), message); return; }
293                                         break;
294                                 
295                                 case '412 Precondition Failed':
296                                         matches=message.match(/Node (\d+) is still used/i);
297                                         if (matches) { throwInUseError(findEntity('Node',matches[1]), message); return; }
298                                         matches=message.match(/relation (\d+) is used/i);
299                                         if (matches) { throwInUseError(findEntity('Relation',matches[1]), message); return; }
300                                         matches=message.match(/Way (\d+) still used/i);
301                                         if (matches) { throwInUseError(findEntity('Way',matches[1]), message); return; }
302                                         matches=message.match(/Cannot update (\w+) (\d+)/i);
303                                         if (matches) { throwEntityError(findEntity(matches[1],matches[2]), message); return; }
304                                         matches=message.match(/Relation with id (\d+)/i);
305                                         if (matches) { throwEntityError(findEntity('Relation',matches[1]), message); return; }
306                                         matches=message.match(/Way (\d+) requires the nodes/i);
307                                         if (matches) { throwEntityError(findEntity('Way',matches[1]), message); return; }
308                                         throwBugError(message); return;
309                                 
310                                 case '404 Not Found':
311                                         throwBugError(message); return;
312                                         
313                                 case '400 Bad Request':
314                                         matches=message.match(/Element (\w+)\/(\d+)/i);
315                                         if (matches) { throwEntityError(findEntity(matches[1],matches[2]), message); return; }
316                                         matches=message.match(/You tried to add \d+ nodes to way (\d+)/i);
317                                         if (matches) { throwEntityError(findEntity('Way',matches[1]), message); return; }
318                                         throwBugError(message); return;
319                         }
320
321                         // Not caught, so just throw a generic server error
322                         throwServerError(message);
323                 }
324
325         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
326             var create:XML = <create version="0.6"/>
327             for each( var id:Number in getIDs() ) {
328                 var entity:Entity = get(id);
329                 if ( id >= 0 || entity.deleted )
330                     continue;
331                     
332                 var xml:XML = serialise(entity);
333                 xml.@changeset = changeset.id;
334                 create.appendChild(xml);
335             }
336             return create.hasComplexContent() ? create : <!-- blank create section -->;
337         }
338
339                 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function, ifUnused:Boolean):XML {
340             var del:XML = <delete version="0.6"/>
341             if (ifUnused) del.@["if-unused"] = "true";
342             for each( var id:Number in getIDs() ) {
343                 var entity:Entity = get(id);
344                 // creates are already included
345                 if ( id < 0 || !entity.deleted || entity.parentsLoaded==ifUnused)
346                     continue;
347                     
348                 var xml:XML = serialise(entity);
349                 xml.@changeset = changeset.id;
350                 del.appendChild(xml);
351             }
352             return del.hasComplexContent() ? del : <!-- blank delete section -->;
353                 }
354
355         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
356             var modify:XML = <modify version="0.6"/>
357             for each( var id:Number in getIDs() ) {
358                 var entity:Entity = get(id);
359                 // creates and deletes are already included
360                 if ( id < 0 || entity.deleted || !entity.isDirty )
361                     continue;
362                     
363                 var xml:XML = serialise(entity);
364                 xml.@changeset = changeset.id;
365                 modify.appendChild(xml);
366             }
367             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
368         }
369
370         private function serialiseNode(node:Node):XML {
371             var xml:XML = serialiseEntityRoot(node); //<node/>
372             serialiseEntityTags(node, xml);
373             xml.@lat = node.lat;
374             xml.@lon = node.lon;
375             return xml;
376         }
377
378         private function serialiseWay(way:Way):XML {
379             var xml:XML = serialiseEntityRoot(way); //<node/>
380             serialiseEntityTags(way, xml);
381             for ( var i:uint = 0; i < way.length; i++ ) {
382                 var nd:XML = <nd/>
383                 nd.@ref = way.getNode(i).id;
384                 xml.appendChild(nd);
385             }
386             return xml;
387         }
388
389         private function serialiseRelation(relation:Relation):XML {
390             var xml:XML = serialiseEntityRoot(relation); //<node/>
391             serialiseEntityTags(relation, xml);
392             for ( var i:uint = 0; i < relation.length; i++ ) {
393                 var relMember:RelationMember = relation.getMember(i);
394                 var member:XML = <member/>
395                 member.@ref = relMember.entity.id;
396                 member.@type = relMember.entity.getType();
397                 member.@role = relMember.role;
398                 xml.appendChild(member);
399             }
400             return xml;
401         }
402         
403                 private function serialiseEntityRoot(entity:Object):XML {
404                         var xml:XML;
405                         if      (entity is Way     ) { xml = <way/> }
406                         else if (entity is Node    ) { xml = <node/> }
407                         else if (entity is Relation) { xml = <relation/> }
408                         xml.@id = entity.id;
409                         xml.@version = entity.version;
410                         return xml;
411                 }
412
413         private function serialiseEntityTags(entity:Entity, xml:XML):void {
414             xml.@id = entity.id;
415             xml.@version = entity.version;
416             for each( var tag:Tag in entity.getTagArray() ) {
417               if (tag.key == 'created_by') {
418                 entity.setTag('created_by', null, MainUndoStack.getGlobalStack().addAction);
419                 continue;
420               }
421               var tagXML:XML = <tag/>
422               tagXML.@k = tag.key;
423               tagXML.@v = tag.value;
424               xml.appendChild(tagXML);
425             }
426         }
427
428         override public function fetchUserTraces(refresh:Boolean=false):void {
429             if (traces_loaded && !refresh) {
430               dispatchEvent(new Event(TRACES_LOADED));
431             } else {
432               sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
433                           tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
434               dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
435             }
436         }
437
438         private function tracesLoadComplete(event:Event):void {
439             clearTraces();
440             var files:XML = new XML(URLLoader(event.target).data);
441             for each(var traceData:XML in files.gpx_file) {
442               var t:Trace = new Trace().fromXML(traceData);
443               addTrace(t);
444             }
445             traces_loaded = true;
446             dispatchEvent(new Event(LOAD_COMPLETED));
447             dispatchEvent(new Event(TRACES_LOADED));
448         }
449
450         override public function fetchTrace(id:Number, callback:Function):void {
451             sendOAuthGet(Connection.apiBaseURL+"gpx/"+id+"/data.xml", 
452                                 function(e:Event):void { 
453                         dispatchEvent(new Event(LOAD_COMPLETED));
454                                         callback(e);
455                                 }, errorOnMapLoad, mapLoadStatus); // needs error handlers
456             dispatchEvent(new Event(LOAD_STARTED)); //specifc to map or reusable?
457         }
458         }
459 }