use getParam directly, and fix indentation
[potlatch2.git] / net / systemeD / halcyon / connection / XMLConnection.as
1 package net.systemeD.halcyon.connection {
2
3     import flash.events.*;
4
5         import flash.system.Security;
6         import flash.net.*;
7     import org.iotashan.oauth.*;
8
9         import net.systemeD.halcyon.MapEvent;
10
11     /**
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
14     */
15         public class XMLConnection extends XMLBaseConnection {
16
17         //public var readConnection:NetConnection;
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             var mapVars:URLVariables = new URLVariables();
32             mapVars.bbox= left+","+bottom+","+right+","+top;
33
34             var mapRequest:URLRequest = new URLRequest(Connection.apiBaseURL+"map");
35             mapRequest.data = mapVars;
36
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));
43                 }
44
45         private function errorOnMapLoad(event:Event):void {
46                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't load the map" } ));
47         }
48         private function mapLoadStatus(event:HTTPStatusEvent):void {
49             trace("loading map status = "+event.status);
50         }
51
52         protected var appID:OAuthConsumer;
53         protected var authToken:OAuthToken;
54         
55             override public function setAppID(id:Object):void {
56                 appID = OAuthConsumer(id);
57             }
58             
59             override public function setAuthToken(id:Object):void {
60                 authToken = OAuthToken(id);
61             }
62
63         /* Get the stored access token, or try setting it up from loader params or passed SharedObject */
64         /* todo: make this private */
65         override public function getAccessToken(data:Object):OAuthToken {
66             if (authToken == null) {
67               var key:String = getParam("oauth_token", null);
68               var secret:String = getParam("oauth_token_secret", null);
69
70               if ( key == null || secret == null ) {
71                   key = data["oauth_token"];
72                   secret = data["oauth_token_secret"];
73               }
74
75               if ( key != null && secret != null ) {
76                   authToken = new OAuthToken(key, secret);
77               }
78             }
79             return authToken;
80         }
81
82         override public function getConsumer():OAuthConsumer {
83             if (appID == null) {
84               var key:String = getParam("oauth_consumer_key", null);
85               var secret:String = getParam("oauth_consumer_secret", null);
86
87               if ( key != null && secret != null ) {
88                   appID = new OAuthConsumer(key, secret);
89               }
90             }
91             return appID;
92         }
93
94         private var httpStatus:int = 0;
95         
96         private function recordStatus(event:HTTPStatusEvent):void {
97             httpStatus = event.status;
98         }
99         
100         private var lastUploadedChangesetTags:Object;
101         
102         override public function createChangeset(tags:Object):void {
103             lastUploadedChangesetTags = tags;
104             
105                 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
106                 var changeset:XML = <changeset />;
107                 for (var tagKey:Object in tags) {
108               var tagXML:XML = <tag/>;
109               tagXML.@k = tagKey;
110               tagXML.@v = tags[tagKey];
111               changesetXML.changeset.appendChild(tagXML);
112             }        
113
114                         sendOAuthPut(Connection.apiBaseURL+"changeset/create",
115                                                  changesetXML,
116                                                  changesetCreateComplete, changesetCreateError, recordStatus);
117             }
118
119         private function changesetCreateComplete(event:Event):void {
120             // response should be a Number changeset id
121             var id:Number = Number(URLLoader(event.target).data);
122             
123             // which means we now have a new changeset!
124             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
125         }
126
127         private function changesetCreateError(event:IOErrorEvent):void {
128             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
129         }
130
131                 override public function closeChangeset():void {
132             var cs:Changeset = getActiveChangeset();
133                         if (!cs) return;
134                         
135                         sendOAuthPut(Connection.apiBaseURL+"changeset/"+cs.id+"/close",
136                                                  null,
137                                                  changesetCloseComplete, changesetCloseError, recordStatus);
138                         closeActiveChangeset();
139                 }
140                 
141                 private function changesetCloseComplete(event:Event):void { }
142                 private function changesetCloseError(event:Event):void { }
143                 // ** TODO: when we get little floating warnings, we can send a happy or sad one up
144
145         private function signedOAuthURL(url:String, method:String):String {
146             // method should be PUT, GET, POST or DELETE
147             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
148             var oauthRequest:OAuthRequest = new OAuthRequest(method, url, null, appID, authToken);
149             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING);
150             return String(urlStr);
151         }
152
153                 private function sendOAuthPut(url:String, xml:XML, onComplete:Function, onError:Function, onStatus:Function):void {
154             // build the request
155             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "PUT"));
156             urlReq.method = "POST";
157                         if (xml) { urlReq.data = xml.toXMLString(); } else { urlReq.data = true; }
158             urlReq.contentType = "application/xml";
159             urlReq.requestHeaders = new Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
160             var loader:URLLoader = new URLLoader();
161             loader.addEventListener(Event.COMPLETE, onComplete);
162             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
163             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
164                 loader.load(urlReq);
165                 }
166
167         private function sendOAuthGet(url:String, onComplete:Function, onError:Function, onStatus:Function):void {
168             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "GET"));
169             urlReq.method = "GET";
170             var loader:URLLoader = new URLLoader();
171             loader.addEventListener(Event.COMPLETE, onComplete);
172             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
173             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
174             loader.load(urlReq);
175         }
176
177         override public function uploadChanges():void {
178             var changeset:Changeset = getActiveChangeset();
179             var upload:XML = <osmChange version="0.6"/>
180             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
181             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
182             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
183             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
184             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
185             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
186             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot));
187             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot));
188             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot));
189
190             // now actually upload them
191             // make an OAuth query
192
193             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
194
195             // build the actual request
196             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "POST"));
197             urlReq.method = "POST";
198             urlReq.data = upload.toXMLString();
199             urlReq.contentType = "text/xml";
200             var loader:URLLoader = new URLLoader();
201             loader.addEventListener(Event.COMPLETE, diffUploadComplete);
202             loader.addEventListener(IOErrorEvent.IO_ERROR, diffUploadError);
203             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
204                 loader.load(urlReq);
205                 
206                 dispatchEvent(new Event(SAVE_STARTED));
207         }
208
209         private function diffUploadComplete(event:Event):void {
210             // response should be XML describing the progress
211             var results:XML = new XML((URLLoader(event.target).data));
212             
213             for each( var update:XML in results.child("*") ) {
214                 var oldID:Number = Number(update.@old_id);
215                 var newID:Number = Number(update.@new_id);
216                 var version:uint = uint(update.@new_version);
217                 var type:String = update.name();
218
219                                 if (newID==0) {
220                                         // delete
221                         if ( type == "node" ) killNode(oldID);
222                         else if ( type == "way" ) killWay(oldID);
223                         else if ( type == "relation" ) killRelation(oldID);
224                                         
225                                 } else {
226                                         // create/update
227                         var entity:Entity;
228                         if ( type == "node" ) entity = getNode(oldID);
229                         else if ( type == "way" ) entity = getWay(oldID);
230                         else if ( type == "relation" ) entity = getRelation(oldID);
231                         entity.markClean(newID, version);
232                 
233                         if ( oldID != newID ) {
234                             if ( type == "node" ) renumberNode(oldID, entity as Node, false);
235                             else if ( type == "way" ) renumberWay(oldID, entity as Way, false);
236                             else if ( type == "relation" ) renumberRelation(oldID, entity as Relation, false);
237                         }
238                                 }
239             }
240
241             dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
242                         freshenActiveChangeset();
243             markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
244             MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
245         }
246
247         private function diffUploadError(event:IOErrorEvent):void {
248                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+httpStatus+" "+event.text } ));
249                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
250         }
251
252         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
253             var create:XML = <create version="0.6"/>
254             for each( var id:Number in getIDs() ) {
255                 var entity:Entity = get(id);
256                 if ( id >= 0 || entity.deleted )
257                     continue;
258                     
259                 var xml:XML = serialise(entity);
260                 xml.@changeset = changeset.id;
261                 create.appendChild(xml);
262             }
263             return create.hasComplexContent() ? create : <!-- blank create section -->;
264         }
265
266                 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
267             var del:XML = <delete version="0.6"/>
268             for each( var id:Number in getIDs() ) {
269                 var entity:Entity = get(id);
270                 // creates are already included
271                 if ( id < 0 || !entity.deleted )
272                     continue;
273                     
274                 var xml:XML = serialise(entity);
275                 xml.@changeset = changeset.id;
276                 del.appendChild(xml);
277             }
278             return del.hasComplexContent() ? del : <!-- blank delete section -->;
279                 }
280
281         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
282             var modify:XML = <modify version="0.6"/>
283             for each( var id:Number in getIDs() ) {
284                 var entity:Entity = get(id);
285                 // creates and deletes are already included
286                 if ( id < 0 || entity.deleted || !entity.isDirty )
287                     continue;
288                     
289                 var xml:XML = serialise(entity);
290                 xml.@changeset = changeset.id;
291                 modify.appendChild(xml);
292             }
293             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
294         }
295
296         private function serialiseNode(node:Node):XML {
297             var xml:XML = serialiseEntityRoot(node); //<node/>
298             serialiseEntityTags(node, xml);
299             xml.@lat = node.lat;
300             xml.@lon = node.lon;
301             return xml;
302         }
303
304         private function serialiseWay(way:Way):XML {
305             var xml:XML = serialiseEntityRoot(way); //<node/>
306             serialiseEntityTags(way, xml);
307             for ( var i:uint = 0; i < way.length; i++ ) {
308                 var nd:XML = <nd/>
309                 nd.@ref = way.getNode(i).id;
310                 xml.appendChild(nd);
311             }
312             return xml;
313         }
314
315         private function serialiseRelation(relation:Relation):XML {
316             var xml:XML = serialiseEntityRoot(relation); //<node/>
317             serialiseEntityTags(relation, xml);
318             for ( var i:uint = 0; i < relation.length; i++ ) {
319                 var relMember:RelationMember = relation.getMember(i);
320                 var member:XML = <member/>
321                 member.@ref = relMember.entity.id;
322                 member.@type = relMember.entity.getType();
323                 member.@role = relMember.role;
324                 xml.appendChild(member);
325             }
326             return xml;
327         }
328         
329                 private function serialiseEntityRoot(entity:Object):XML {
330                         var xml:XML;
331                         if      (entity is Way     ) { xml = <way/> }
332                         else if (entity is Node    ) { xml = <node/> }
333                         else if (entity is Relation) { xml = <relation/> }
334                         xml.@id = entity.id;
335                         xml.@version = entity.version;
336                         return xml;
337                 }
338
339         private function serialiseEntityTags(entity:Entity, xml:XML):void {
340             xml.@id = entity.id;
341             xml.@version = entity.version;
342             for each( var tag:Tag in entity.getTagArray() ) {
343               if (tag.key == 'created_by') {
344                 entity.setTag('created_by', null, MainUndoStack.getGlobalStack().addAction);
345                 continue;
346               }
347               var tagXML:XML = <tag/>
348               tagXML.@k = tag.key;
349               tagXML.@v = tag.value;
350               xml.appendChild(tagXML);
351             }
352         }
353
354         override public function fetchUserTraces(refresh:Boolean=false):void {
355             if (traces_loaded && !refresh) {
356               dispatchEvent(new Event(TRACES_LOADED));
357             } else {
358               sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
359                           tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
360               dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
361             }
362         }
363
364         private function tracesLoadComplete(event:Event):void {
365             clearTraces();
366             var files:XML = new XML(URLLoader(event.target).data);
367             for each(var traceData:XML in files.gpx_file) {
368               var t:Trace = new Trace().fromXML(traceData);
369               addTrace(t);
370             }
371             traces_loaded = true;
372             dispatchEvent(new Event(LOAD_COMPLETED));
373             dispatchEvent(new Event(TRACES_LOADED));
374         }
375
376         override public function fetchTrace(id:Number, callback:Function):void {
377             sendOAuthGet(Connection.apiBaseURL+"gpx/"+id+"/data.xml", callback, errorOnMapLoad, mapLoadStatus); // needs error handlers
378             dispatchEvent(new Event(LOAD_STARTED)); //specifc to map or reusable?
379         }
380         }
381 }