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