slash and burn trace statements, and fix areas on vector background layers
[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         import mx.controls.Alert;
9
10         import net.systemeD.halcyon.Globals;
11
12         public class XMLConnection extends XMLBaseConnection {
13
14         //public var readConnection:NetConnection;
15
16                 public function XMLConnection() {
17
18                         if (Connection.policyURL!='')
19                 Security.loadPolicyFile(Connection.policyURL);
20             var oauthPolicy:String = Connection.getParam("oauth_policy", "");
21             if ( oauthPolicy != "" ) {
22                 Security.loadPolicyFile(oauthPolicy);
23             }
24                 }
25                 
26                 override public function loadBbox(left:Number,right:Number,
27                                                                 top:Number,bottom:Number):void {
28             var mapVars:URLVariables = new URLVariables();
29             mapVars.bbox= left+","+bottom+","+right+","+top;
30
31             var mapRequest:URLRequest = new URLRequest(Connection.apiBaseURL+"map");
32             mapRequest.data = mapVars;
33
34             var mapLoader:URLLoader = new URLLoader();
35             mapLoader.addEventListener(Event.COMPLETE, loadedMap);
36             mapLoader.addEventListener(IOErrorEvent.IO_ERROR, errorOnMapLoad);
37             mapLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, mapLoadStatus);
38             mapLoader.load(mapRequest);
39             dispatchEvent(new Event(LOAD_STARTED));
40                 }
41
42         private function errorOnMapLoad(event:Event):void {
43                         Alert.show("Couldn't load the map", 'Error', mx.controls.Alert.OK);
44         }
45         private function mapLoadStatus(event:HTTPStatusEvent):void {
46             trace("loading map status = "+event.status);
47         }
48
49         protected var appID:OAuthConsumer;
50         protected var authToken:OAuthToken;
51         
52             override public function setAppID(id:Object):void {
53                 appID = OAuthConsumer(id);
54             }
55             
56             override public function setAuthToken(id:Object):void {
57                 authToken = OAuthToken(id);
58             }
59
60         private var httpStatus:int = 0;
61         
62         private function recordStatus(event:HTTPStatusEvent):void {
63             httpStatus = event.status;
64         }
65         
66         private var lastUploadedChangesetTags:Object;
67         
68         override public function createChangeset(tags:Object):void {
69             lastUploadedChangesetTags = tags;
70             
71                 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
72                 var changeset:XML = <changeset />;
73                 for (var tagKey:Object in tags) {
74               var tagXML:XML = <tag/>;
75               tagXML.@k = tagKey;
76               tagXML.@v = tags[tagKey];
77               changesetXML.changeset.appendChild(tagXML);
78             }        
79
80             // make an OAuth query
81             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
82             var url:String = Connection.apiBaseURL+"changeset/create";
83             //var params:Object = { _method: "PUT" };
84             var oauthRequest:OAuthRequest = new OAuthRequest("PUT", url, null, appID, authToken);
85             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
86
87             // build the actual request
88             var urlReq:URLRequest = new URLRequest(String(urlStr));
89             urlReq.method = "POST";
90             urlReq.data = changesetXML.toXMLString();
91             urlReq.contentType = "application/xml";
92             urlReq.requestHeaders = new Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
93             var loader:URLLoader = new URLLoader();
94             loader.addEventListener(Event.COMPLETE, changesetCreateComplete);
95             loader.addEventListener(IOErrorEvent.IO_ERROR, changesetCreateError);
96             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
97                 loader.load(urlReq);
98             }
99
100         private function changesetCreateComplete(event:Event):void {
101             // response should be a Number changeset id
102             var id:Number = Number(URLLoader(event.target).data);
103             
104             // which means we now have a new changeset!
105             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
106         }
107
108         private function changesetCreateError(event:IOErrorEvent):void {
109             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
110         }
111         
112         override public function uploadChanges():void {
113             var changeset:Changeset = getActiveChangeset();
114             var upload:XML = <osmChange version="0.6"/>
115             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
116             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
117             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
118             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
119             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
120             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
121             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot));
122             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot));
123             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot));
124
125             // now actually upload them
126             // make an OAuth query
127             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
128             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
129             var oauthRequest:OAuthRequest = new OAuthRequest("POST", url, null, appID, authToken);
130             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
131
132             // build the actual request
133             var urlReq:URLRequest = new URLRequest(String(urlStr));
134             urlReq.method = "POST";
135             urlReq.data = upload.toXMLString();
136             urlReq.contentType = "text/xml";
137             var loader:URLLoader = new URLLoader();
138             loader.addEventListener(Event.COMPLETE, diffUploadComplete);
139             loader.addEventListener(IOErrorEvent.IO_ERROR, diffUploadError);
140             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
141                 loader.load(urlReq);
142                 
143                 dispatchEvent(new Event(SAVE_STARTED));
144         }
145
146         private function diffUploadComplete(event:Event):void {
147             // response should be XML describing the progress
148             var results:XML = new XML((URLLoader(event.target).data));
149             
150             for each( var update:XML in results.child("*") ) {
151                 var oldID:Number = Number(update.@old_id);
152                 var newID:Number = Number(update.@new_id);
153                 var version:uint = uint(update.@new_version);
154                 var type:String = update.name();
155
156                                 if (newID==0) {
157                                         // delete
158                         if ( type == "node" ) killNode(oldID);
159                         else if ( type == "way" ) killWay(oldID);
160                         else if ( type == "relation" ) killRelation(oldID);
161                                         
162                                 } else {
163                                         // create/update
164                         var entity:Entity;
165                         if ( type == "node" ) entity = getNode(oldID);
166                         else if ( type == "way" ) entity = getWay(oldID);
167                         else if ( type == "relation" ) entity = getRelation(oldID);
168                         entity.markClean(newID, version);
169                 
170                         if ( oldID != newID ) {
171                             if ( type == "node" ) renumberNode(oldID, entity as Node, false);
172                             else if ( type == "way" ) renumberWay(oldID, entity as Way, false);
173                             else if ( type == "relation" ) renumberRelation(oldID, entity as Relation, false);
174                         }
175                                 }
176             }
177
178                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
179                 markClean();
180         }
181
182         private function diffUploadError(event:IOErrorEvent):void {
183                         Alert.show("Couldn't upload data: "+httpStatus+" "+event.text, 'Error', mx.controls.Alert.OK);
184                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
185         }
186
187         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
188             var create:XML = <create version="0.6"/>
189             for each( var id:Number in getIDs() ) {
190                 var entity:Entity = get(id);
191                 if ( id >= 0 || entity.deleted )
192                     continue;
193                     
194                 var xml:XML = serialise(entity);
195                 xml.@changeset = changeset.id;
196                 create.appendChild(xml);
197             }
198             return create.hasComplexContent() ? create : <!-- blank create section -->;
199         }
200
201                 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
202             var del:XML = <delete version="0.6"/>
203             for each( var id:Number in getIDs() ) {
204                 var entity:Entity = get(id);
205                 // creates are already included
206                 if ( id < 0 || !entity.deleted )
207                     continue;
208                     
209                 var xml:XML = serialise(entity);
210                 xml.@changeset = changeset.id;
211                 del.appendChild(xml);
212             }
213             return del.hasComplexContent() ? del : <!-- blank delete section -->;
214                 }
215
216         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
217             var modify:XML = <modify version="0.6"/>
218             for each( var id:Number in getIDs() ) {
219                 var entity:Entity = get(id);
220                 // creates and deletes are already included
221                 if ( id < 0 || entity.deleted || !entity.isDirty )
222                     continue;
223                     
224                 var xml:XML = serialise(entity);
225                 xml.@changeset = changeset.id;
226                 modify.appendChild(xml);
227             }
228             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
229         }
230
231         private function serialiseNode(node:Node):XML {
232             var xml:XML = serialiseEntityRoot(node); //<node/>
233             serialiseEntityTags(node, xml);
234             xml.@lat = node.lat;
235             xml.@lon = node.lon;
236             return xml;
237         }
238
239         private function serialiseWay(way:Way):XML {
240             var xml:XML = serialiseEntityRoot(way); //<node/>
241             serialiseEntityTags(way, xml);
242             for ( var i:uint = 0; i < way.length; i++ ) {
243                 var nd:XML = <nd/>
244                 nd.@ref = way.getNode(i).id;
245                 xml.appendChild(nd);
246             }
247             return xml;
248         }
249
250         private function serialiseRelation(relation:Relation):XML {
251             var xml:XML = serialiseEntityRoot(relation); //<node/>
252             serialiseEntityTags(relation, xml);
253             for ( var i:uint = 0; i < relation.length; i++ ) {
254                 var relMember:RelationMember = relation.getMember(i);
255                 var member:XML = <member/>
256                 member.@ref = relMember.entity.id;
257                 member.@type = relMember.entity.getType();
258                 member.@role = relMember.role;
259                 xml.appendChild(member);
260             }
261             return xml;
262         }
263         
264                 private function serialiseEntityRoot(entity:Object):XML {
265                         var xml:XML;
266                         if      (entity is Way     ) { xml = <way/> }
267                         else if (entity is Node    ) { xml = <node/> }
268                         else if (entity is Relation) { xml = <relation/> }
269                         xml.@id = entity.id;
270                         xml.@version = entity.version;
271                         return xml;
272                 }
273
274         private function serialiseEntityTags(entity:Entity, xml:XML):void {
275             xml.@id = entity.id;
276             xml.@version = entity.version;
277             for each( var tag:Tag in entity.getTagArray() ) {
278               var tagXML:XML = <tag/>
279               tagXML.@k = tag.key;
280               tagXML.@v = tag.value;
281               xml.appendChild(tagXML);
282             }
283         }
284
285         }
286 }