refactor EditController to make it stateful, and add addWayNodes functionality with...
[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
10         public class XMLConnection extends Connection {
11
12         //public var readConnection:NetConnection;
13
14                 public function XMLConnection() {
15
16                         if (Connection.policyURL!='')
17                 Security.loadPolicyFile(Connection.policyURL);
18             var oauthPolicy:String = Connection.getParam("oauth_policy", "");
19             if ( oauthPolicy != "" ) {
20                 trace(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.load(mapRequest);
36             dispatchEvent(new Event(LOAD_STARTED));
37                 }
38
39         private function parseTags(tagElements:XMLList):Object {
40             var tags:Object = {};
41             for each (var tagEl:XML in tagElements)
42                 tags[tagEl.@k] = tagEl.@v;
43             return tags;
44         }
45
46         private function loadedMap(event:Event):void {
47             dispatchEvent(new Event(LOAD_COMPLETED));
48
49             var map:XML = new XML(URLLoader(event.target).data);
50             var id:Number;
51             var version:uint;
52             var tags:Object;
53
54             for each(var nodeData:XML in map.node) {
55                 id = Number(nodeData.@id);
56                 version = uint(nodeData.@version);
57
58                 var node:Node = getNode(id);
59                 if ( node == null ) {
60                     var lat:Number = Number(nodeData.@lat);
61                     var lon:Number = Number(nodeData.@lon);
62                     tags = parseTags(nodeData.tag);
63                     setNode(new Node(id, version, tags, true, lat, lon));
64                 }
65             }
66
67             for each(var data:XML in map.way) {
68                 id = Number(data.@id);
69                 version = uint(data.@version);
70
71                 var way:Way = getWay(id);
72                 if ( way == null ) {
73                     var nodes:Array = [];
74                     for each(var nd:XML in data.nd)
75                         nodes.push(getNode(Number(nd.@ref)));
76                     tags = parseTags(data.tag);
77                     setWay(new Way(id, version, tags,true,  nodes));
78                 }
79             }
80         }
81
82         protected var appID:OAuthConsumer;
83         protected var authToken:OAuthToken;
84         
85             override public function setAppID(id:Object):void {
86                 appID = OAuthConsumer(id);
87             }
88             
89             override public function setAuthToken(id:Object):void {
90                 authToken = OAuthToken(id);
91             }
92
93         private var httpStatus:int = 0;
94         
95         private function recordStatus(event:HTTPStatusEvent):void {
96             httpStatus = event.status;
97         }
98         
99         private var lastUploadedChangesetTags:Object;
100         
101         override public function createChangeset(tags:Object):void {
102             lastUploadedChangesetTags = tags;
103             
104                 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
105                 var changeset:XML = <changeset />;
106                 for (var tagKey:Object in tags) {
107               var tagXML:XML = <tag/>;
108               tagXML.@k = tagKey;
109               tagXML.@v = tags[tagKey];
110               changesetXML.changeset.appendChild(tagXML);
111             }        
112
113             // make an OAuth query
114             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
115             var url:String = Connection.apiBaseURL+"changeset/create";
116             //var params:Object = { _method: "PUT" };
117             var oauthRequest:OAuthRequest = new OAuthRequest("PUT", url, null, appID, authToken);
118             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
119
120             // build the actual request
121             var urlReq:URLRequest = new URLRequest(String(urlStr));
122             urlReq.method = "POST";
123             urlReq.data = changesetXML.toXMLString();
124             urlReq.contentType = "application/xml";
125             urlReq.requestHeaders = new Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
126             var loader:URLLoader = new URLLoader();
127             loader.addEventListener(Event.COMPLETE, changesetCreateComplete);
128             loader.addEventListener(IOErrorEvent.IO_ERROR, changesetCreateError);
129             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
130                 loader.load(urlReq);
131             }
132
133         private function changesetCreateComplete(event:Event):void {
134             // response should be a Number changeset id
135             var id:Number = Number(URLLoader(event.target).data);
136             
137             // which means we now have a new changeset!
138             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
139         }
140
141         private function changesetCreateError(event:IOErrorEvent):void {
142             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
143         }
144         
145         override public function uploadChanges():void {
146             var changeset:Changeset = getActiveChangeset();
147             var upload:XML = <osmChange version="0.6"/>
148             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
149             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
150             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
151             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
152             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
153             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
154
155             // *** TODO *** deleting items
156             
157             // now actually upload them
158             // make an OAuth query
159             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
160             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
161             var oauthRequest:OAuthRequest = new OAuthRequest("POST", url, null, appID, authToken);
162             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
163
164             // build the actual request
165             var urlReq:URLRequest = new URLRequest(String(urlStr));
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                 var entity:Entity;
189                 if ( type == "node" ) entity = getNode(oldID);
190                 else if ( type == "way" ) entity = getWay(oldID);
191                 else if ( type == "relation" ) entity = getRelation(oldID);
192                 entity.markClean(newID, version);
193                 
194                 if ( oldID != newID ) {
195                     if ( type == "node" ) renumberNode(oldID, entity as Node);
196                     else if ( type == "way" ) renumberWay(oldID, entity as Way);
197                     else if ( type == "relation" ) renumberRelation(oldID, entity as Relation);
198                 }
199                 // *** TODO *** handle deleting
200             }
201
202                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
203         }
204
205         private function diffUploadError(event:IOErrorEvent):void {
206             trace("error "+URLLoader(event.target).data + " "+httpStatus+ " " + event.text);
207
208                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
209         }
210
211         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
212             var create:XML = <create version="0.6"/>
213             for each( var id:Number in getIDs() ) {
214                 if ( id >= 0 )
215                     continue;
216                     
217                 var entity:Object = get(id);
218                 var xml:XML = serialise(entity);
219                 xml.@changeset = changeset.id;
220                 create.appendChild(xml);
221             }
222             return create.hasComplexContent() ? create : <!-- blank create section -->;
223         }
224
225         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
226             var modify:XML = <modify version="0.6"/>
227             for each( var id:Number in getIDs() ) {
228                 var entity:Entity = get(id);
229                 // creates are already included
230                 if ( id < 0 || !entity.isDirty )
231                     continue;
232                     
233                 var xml:XML = serialise(entity);
234                 xml.@changeset = changeset.id;
235                 modify.appendChild(xml);
236             }
237             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
238         }
239
240         private function serialiseNode(node:Node):XML {
241             var xml:XML = <node/>
242             serialiseEntity(node, xml);
243             xml.@lat = node.lat;
244             xml.@lon = node.lon;
245             return xml;
246         }
247
248         private function serialiseWay(way:Way):XML {
249             var xml:XML = <way/>
250             serialiseEntity(way, xml);
251             for ( var i:uint = 0; i < way.length; i++ ) {
252                 var nd:XML = <nd/>
253                 nd.@ref = way.getNode(i).id;
254                 xml.appendChild(nd);
255             }
256             return xml;
257         }
258
259         private function serialiseRelation(relation:Relation):XML {
260             var xml:XML = <relation/>
261             serialiseEntity(relation, xml);
262             for ( var i:uint = 0; i < relation.length; i++ ) {
263                 var relMember:RelationMember = relation.getMember(i);
264                 var member:XML = <member/>
265                 member.@ref = relMember.entity.id;
266                 member.@type = relMember.entity.getType();
267                 member.@role = relMember.role;
268                 xml.appendChild(member);
269             }
270             return xml;
271         }
272         
273         private function serialiseEntity(entity:Entity, xml:XML):void {
274             xml.@id = entity.id;
275             xml.@version = entity.version;
276             for each( var tag:Tag in entity.getTagArray() ) {
277               var tagXML:XML = <tag/>
278               tagXML.@k = tag.key;
279               tagXML.@v = tag.value;
280               xml.appendChild(tagXML);
281             }
282         }
283         }
284 }