placeholders for second half of the code (will need a small API update before this...
[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 setAuthToken(id:Object):void {
56                 authToken = OAuthToken(id);
57             }
58
59         override public function hasAccessToken():Boolean {
60             return !(getAccessToken() == null);
61         }
62
63         override public function setAccessToken(key:String, secret:String):void {
64             if (key && secret) {
65               authToken = new OAuthToken(key, secret);
66             }
67         }
68
69         /* Get the stored access token, or try setting it up from loader params */
70         private function getAccessToken():OAuthToken {
71             if (authToken == null) {
72               var key:String = getParam("oauth_token", null);
73               var secret:String = getParam("oauth_token_secret", null);
74
75               if ( key != null && secret != null ) {
76                   authToken = new OAuthToken(key, secret);
77               }
78             }
79             return authToken;
80         }
81
82         private 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, getConsumer(), 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.dataFormat = URLLoaderDataFormat.BINARY;
202             loader.addEventListener(Event.COMPLETE, diffUploadComplete);
203             loader.addEventListener(IOErrorEvent.IO_ERROR, function(event:IOErrorEvent):void { trace(urlReq.data); diffUploadError(event); } );
204             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
205                 loader.load(urlReq);
206                 
207                 dispatchEvent(new Event(SAVE_STARTED));
208         }
209
210         private function diffUploadComplete(event:Event):void {
211             // response should be XML describing the progress
212             var results:XML = new XML((URLLoader(event.target).data));
213             
214             for each( var update:XML in results.child("*") ) {
215                 var oldID:Number = Number(update.@old_id);
216                 var newID:Number = Number(update.@new_id);
217                 var version:uint = uint(update.@new_version);
218                 var type:String = update.name();
219
220                                 if (newID==0) {
221                                         // delete
222                         if      (type == "node"    ) { killNode(oldID); }
223                         else if (type == "way"     ) { killWay(oldID); }
224                         else if (type == "relation") { killRelation(oldID); }
225                                         
226                                 } else {
227                                         // create/update
228                         if      (type == "node"    ) { renumberNode(oldID, newID, version); getNode(newID).markClean(); }
229                         else if (type == "way"     ) { renumberWay(oldID, newID, version); getWay(newID).markClean(); }
230                         else if (type == "relation") { renumberRelation(oldID, newID, version); getRelation(newID).markClean(); }
231                                 }
232             }
233
234             dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
235                         freshenActiveChangeset();
236             markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
237             MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
238         }
239
240         private function diffUploadError(event:IOErrorEvent):void {
241                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+httpStatus+" "+event.text } ));
242                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
243         }
244
245         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
246             var create:XML = <create version="0.6"/>
247             for each( var id:Number in getIDs() ) {
248                 var entity:Entity = get(id);
249                 if ( id >= 0 || entity.deleted )
250                     continue;
251                     
252                 var xml:XML = serialise(entity);
253                 xml.@changeset = changeset.id;
254                 create.appendChild(xml);
255             }
256             return create.hasComplexContent() ? create : <!-- blank create section -->;
257         }
258
259                 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
260             var del:XML = <delete version="0.6"/>
261             for each( var id:Number in getIDs() ) {
262                 var entity:Entity = get(id);
263                 // creates are already included
264                 if ( id < 0 || !entity.deleted )
265                     continue;
266                     
267                 var xml:XML = serialise(entity);
268                 // ** if parentsLoaded==false, do a soft delete only
269                 xml.@changeset = changeset.id;
270                 del.appendChild(xml);
271             }
272             return del.hasComplexContent() ? del : <!-- blank delete section -->;
273                 }
274
275         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
276             var modify:XML = <modify version="0.6"/>
277             for each( var id:Number in getIDs() ) {
278                 var entity:Entity = get(id);
279                 // creates and deletes are already included
280                 if ( id < 0 || entity.deleted || !entity.isDirty )
281                     continue;
282                     
283                 var xml:XML = serialise(entity);
284                 xml.@changeset = changeset.id;
285                 modify.appendChild(xml);
286             }
287             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
288         }
289
290         private function serialiseNode(node:Node):XML {
291             var xml:XML = serialiseEntityRoot(node); //<node/>
292             serialiseEntityTags(node, xml);
293             xml.@lat = node.lat;
294             xml.@lon = node.lon;
295             return xml;
296         }
297
298         private function serialiseWay(way:Way):XML {
299             var xml:XML = serialiseEntityRoot(way); //<node/>
300             serialiseEntityTags(way, xml);
301             for ( var i:uint = 0; i < way.length; i++ ) {
302                 var nd:XML = <nd/>
303                 nd.@ref = way.getNode(i).id;
304                 xml.appendChild(nd);
305             }
306             return xml;
307         }
308
309         private function serialiseRelation(relation:Relation):XML {
310             var xml:XML = serialiseEntityRoot(relation); //<node/>
311             serialiseEntityTags(relation, xml);
312             for ( var i:uint = 0; i < relation.length; i++ ) {
313                 var relMember:RelationMember = relation.getMember(i);
314                 var member:XML = <member/>
315                 member.@ref = relMember.entity.id;
316                 member.@type = relMember.entity.getType();
317                 member.@role = relMember.role;
318                 xml.appendChild(member);
319             }
320             return xml;
321         }
322         
323                 private function serialiseEntityRoot(entity:Object):XML {
324                         var xml:XML;
325                         if      (entity is Way     ) { xml = <way/> }
326                         else if (entity is Node    ) { xml = <node/> }
327                         else if (entity is Relation) { xml = <relation/> }
328                         xml.@id = entity.id;
329                         xml.@version = entity.version;
330                         return xml;
331                 }
332
333         private function serialiseEntityTags(entity:Entity, xml:XML):void {
334             xml.@id = entity.id;
335             xml.@version = entity.version;
336             for each( var tag:Tag in entity.getTagArray() ) {
337               if (tag.key == 'created_by') {
338                 entity.setTag('created_by', null, MainUndoStack.getGlobalStack().addAction);
339                 continue;
340               }
341               var tagXML:XML = <tag/>
342               tagXML.@k = tag.key;
343               tagXML.@v = tag.value;
344               xml.appendChild(tagXML);
345             }
346         }
347
348         override public function fetchUserTraces(refresh:Boolean=false):void {
349             if (traces_loaded && !refresh) {
350               dispatchEvent(new Event(TRACES_LOADED));
351             } else {
352               sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
353                           tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
354               dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
355             }
356         }
357
358         private function tracesLoadComplete(event:Event):void {
359             clearTraces();
360             var files:XML = new XML(URLLoader(event.target).data);
361             for each(var traceData:XML in files.gpx_file) {
362               var t:Trace = new Trace().fromXML(traceData);
363               addTrace(t);
364             }
365             traces_loaded = true;
366             dispatchEvent(new Event(LOAD_COMPLETED));
367             dispatchEvent(new Event(TRACES_LOADED));
368         }
369
370         override public function fetchTrace(id:Number, callback:Function):void {
371             sendOAuthGet(Connection.apiBaseURL+"gpx/"+id+"/data.xml", 
372                                 function(e:Event):void { 
373                         dispatchEvent(new Event(LOAD_COMPLETED));
374                                         callback(e);
375                                 }, errorOnMapLoad, mapLoadStatus); // needs error handlers
376             dispatchEvent(new Event(LOAD_STARTED)); //specifc to map or reusable?
377         }
378         }
379 }