Remove the external oauth-get-signing. Only XMLConnection should be fetching things...
[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         private var httpStatus:int = 0;
64         
65         private function recordStatus(event:HTTPStatusEvent):void {
66             httpStatus = event.status;
67         }
68         
69         private var lastUploadedChangesetTags:Object;
70         
71         override public function createChangeset(tags:Object):void {
72             lastUploadedChangesetTags = tags;
73             
74                 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
75                 var changeset:XML = <changeset />;
76                 for (var tagKey:Object in tags) {
77               var tagXML:XML = <tag/>;
78               tagXML.@k = tagKey;
79               tagXML.@v = tags[tagKey];
80               changesetXML.changeset.appendChild(tagXML);
81             }        
82
83                         sendOAuthPut(Connection.apiBaseURL+"changeset/create",
84                                                  changesetXML,
85                                                  changesetCreateComplete, changesetCreateError, recordStatus);
86             }
87
88         private function changesetCreateComplete(event:Event):void {
89             // response should be a Number changeset id
90             var id:Number = Number(URLLoader(event.target).data);
91             
92             // which means we now have a new changeset!
93             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
94         }
95
96         private function changesetCreateError(event:IOErrorEvent):void {
97             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
98         }
99
100                 override public function closeChangeset():void {
101             var cs:Changeset = getActiveChangeset();
102                         if (!cs) return;
103                         
104                         sendOAuthPut(Connection.apiBaseURL+"changeset/"+cs.id+"/close",
105                                                  null,
106                                                  changesetCloseComplete, changesetCloseError, recordStatus);
107                         closeActiveChangeset();
108                 }
109                 
110                 private function changesetCloseComplete(event:Event):void { }
111                 private function changesetCloseError(event:Event):void { }
112                 // ** TODO: when we get little floating warnings, we can send a happy or sad one up
113
114         private function signedOAuthURL(url:String, method:String):String {
115             // method should be PUT, GET, POST or DELETE
116             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
117             var oauthRequest:OAuthRequest = new OAuthRequest(method, url, null, appID, authToken);
118             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING);
119             return String(urlStr);
120         }
121
122                 private function sendOAuthPut(url:String, xml:XML, onComplete:Function, onError:Function, onStatus:Function):void {
123             // build the request
124             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "PUT"));
125             urlReq.method = "POST";
126                         if (xml) { urlReq.data = xml.toXMLString(); } else { urlReq.data = true; }
127             urlReq.contentType = "application/xml";
128             urlReq.requestHeaders = new Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
129             var loader:URLLoader = new URLLoader();
130             loader.addEventListener(Event.COMPLETE, onComplete);
131             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
132             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
133                 loader.load(urlReq);
134                 }
135
136         private function sendOAuthGet(url:String, onComplete:Function, onError:Function, onStatus:Function):void {
137             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "GET"));
138             urlReq.method = "GET";
139             var loader:URLLoader = new URLLoader();
140             loader.addEventListener(Event.COMPLETE, onComplete);
141             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
142             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
143             loader.load(urlReq);
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               if (tag.key == 'created_by') {
313                 entity.setTag('created_by', null, MainUndoStack.getGlobalStack().addAction);
314                 continue;
315               }
316               var tagXML:XML = <tag/>
317               tagXML.@k = tag.key;
318               tagXML.@v = tag.value;
319               xml.appendChild(tagXML);
320             }
321         }
322
323         override public function fetchUserTraces():void {
324             sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
325                          tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
326             dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
327         }
328
329         private function tracesLoadComplete(event:Event):void {
330             clearTraces();
331             var files:XML = new XML(URLLoader(event.target).data);
332             for each(var traceData:XML in files.gpx_file) {
333               var t:Trace = new Trace().fromXML(traceData);
334               addTrace(t);
335             }
336             dispatchEvent(new Event(LOAD_COMPLETED));
337             dispatchEvent(new Event(TRACES_LOADED));
338         }
339
340         override public function fetchTrace(id:Number, callback:Function):void {
341             sendOAuthGet(Connection.apiBaseURL+"gpx/"+id+"/data.xml", callback, errorOnMapLoad, mapLoadStatus); // needs error handlers
342             dispatchEvent(new Event(LOAD_STARTED)); //specifc to map or reusable?
343         }
344         }
345 }