use X_HTTP... header to simulate PUT
[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, 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, 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                 // *** TODO *** handle renumbering of creates, and deleting
195             }
196
197                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
198         }
199
200         private function diffUploadError(event:IOErrorEvent):void {
201             trace("error "+URLLoader(event.target).data + " "+httpStatus+ " " + event.text);
202
203                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
204         }
205
206         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
207             var create:XML = <create version="0.6"/>
208             for each( var id:Number in getIDs() ) {
209                 if ( id >= 0 )
210                     continue;
211                     
212                 var entity:Object = get(id);
213                 var xml:XML = serialise(entity);
214                 xml.@changeset = changeset.id;
215                 create.appendChild(xml);
216             }
217             return create.hasComplexContent() ? create : <!-- blank create section -->;
218         }
219
220         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
221             var modify:XML = <modify version="0.6"/>
222             for each( var id:Number in getIDs() ) {
223                 var entity:Entity = get(id);
224                 // creates are already included
225                 if ( id < 0 || !entity.isDirty )
226                     continue;
227                     
228                 var xml:XML = serialise(entity);
229                 xml.@changeset = changeset.id;
230                 modify.appendChild(xml);
231             }
232             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
233         }
234
235         private function serialiseNode(node:Node):XML {
236             var xml:XML = <node/>
237             serialiseEntity(node, xml);
238             xml.@lat = node.lat;
239             xml.@lon = node.lon;
240             return xml;
241         }
242
243         private function serialiseWay(way:Way):XML {
244             var xml:XML = <way/>
245             serialiseEntity(way, xml);
246             for ( var i:uint = 0; i < way.length; i++ ) {
247                 var nd:XML = <nd/>
248                 nd.@ref = way.getNode(i).id;
249                 xml.appendChild(nd);
250             }
251             return xml;
252         }
253
254         private function serialiseRelation(relation:Relation):XML {
255             var xml:XML = <relation/>
256             serialiseEntity(relation, xml);
257             for ( var i:uint = 0; i < relation.length; i++ ) {
258                 var relMember:RelationMember = relation.getMember(i);
259                 var member:XML = <member/>
260                 member.@ref = relMember.entity.id;
261                 member.@type = relMember.entity.getType();
262                 member.@role = relMember.role;
263                 xml.appendChild(member);
264             }
265             return xml;
266         }
267         
268         private function serialiseEntity(entity:Entity, xml:XML):void {
269             xml.@id = entity.id;
270             xml.@version = entity.version;
271             for each( var tag:Tag in entity.getTagArray() ) {
272               var tagXML:XML = <tag/>
273               tagXML.@k = tag.key;
274               tagXML.@v = tag.value;
275               xml.appendChild(tagXML);
276             }
277         }
278         }
279 }