download a crossdomain policy for oauth
[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("POST", url, params, 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             var loader:URLLoader = new URLLoader();
126             loader.addEventListener(Event.COMPLETE, changesetCreateComplete);
127             loader.addEventListener(IOErrorEvent.IO_ERROR, changesetCreateError);
128             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
129                 loader.load(urlReq);
130             }
131
132         private function changesetCreateComplete(event:Event):void {
133             // response should be a Number changeset id
134             var id:Number = Number(URLLoader(event.target).data);
135             
136             // which means we now have a new changeset!
137             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
138         }
139
140         private function changesetCreateError(event:IOErrorEvent):void {
141             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
142         }
143         
144         override public function uploadChanges():void {
145             var changeset:Changeset = getActiveChangeset();
146             var upload:XML = <osmChange version="0.6"/>
147             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
148             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
149             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
150             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
151             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
152             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
153             
154             // *** TODO *** deleting items
155             
156             // now actually upload them
157             // make an OAuth query
158             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
159             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
160             var oauthRequest:OAuthRequest = new OAuthRequest("POST", url, null, appID, authToken);
161             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
162
163             // build the actual request
164             var urlReq:URLRequest = new URLRequest(String(urlStr));
165             urlReq.method = "POST";
166             urlReq.data = upload.toXMLString();
167             urlReq.contentType = "text/xml";
168             var loader:URLLoader = new URLLoader();
169             loader.addEventListener(Event.COMPLETE, diffUploadComplete);
170             loader.addEventListener(IOErrorEvent.IO_ERROR, diffUploadError);
171             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
172                 loader.load(urlReq);
173                 
174                 dispatchEvent(new Event(SAVE_STARTED));
175         }
176
177         private function diffUploadComplete(event:Event):void {
178             // response should be XML describing the progress
179             var results:XML = new XML((URLLoader(event.target).data));
180             
181             for each( var update:XML in results.child("*") ) {
182                 var oldID:Number = Number(update.@old_id);
183                 var newID:Number = Number(update.@new_id);
184                 var version:uint = uint(update.@new_version);
185                 var type:String = update.name();
186                 
187                 var entity:Entity;
188                 if ( type == "node" ) entity = getNode(oldID);
189                 else if ( type == "way" ) entity = getWay(oldID);
190                 else if ( type == "relation" ) entity = getRelation(oldID);
191                 entity.markClean(newID, version);
192                 
193                 // *** TODO *** handle renumbering of creates, and deleting
194             }
195
196                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
197         }
198
199         private function diffUploadError(event:IOErrorEvent):void {
200             trace("error "+URLLoader(event.target).data + " "+httpStatus+ " " + event.text);
201
202                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
203         }
204
205         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
206             var create:XML = <create version="0.6"/>
207             for each( var id:Number in getIDs() ) {
208                 if ( id >= 0 )
209                     continue;
210                     
211                 var entity:Object = get(id);
212                 var xml:XML = serialise(entity);
213                 xml.@changeset = changeset.id;
214                 create.appendChild(xml);
215             }
216             return create.hasComplexContent() ? create : <!-- blank create section -->;
217         }
218
219         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
220             var modify:XML = <modify version="0.6"/>
221             for each( var id:Number in getIDs() ) {
222                 var entity:Entity = get(id);
223                 // creates are already included
224                 if ( id < 0 || !entity.isDirty )
225                     continue;
226                     
227                 var xml:XML = serialise(entity);
228                 xml.@changeset = changeset.id;
229                 modify.appendChild(xml);
230             }
231             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
232         }
233
234         private function serialiseNode(node:Node):XML {
235             var xml:XML = <node/>
236             serialiseEntity(node, xml);
237             xml.@lat = node.lat;
238             xml.@lon = node.lon;
239             return xml;
240         }
241
242         private function serialiseWay(way:Way):XML {
243             var xml:XML = <way/>
244             serialiseEntity(way, xml);
245             for ( var i:uint = 0; i < way.length; i++ ) {
246                 var nd:XML = <nd/>
247                 nd.@ref = way.getNode(i).id;
248                 xml.appendChild(nd);
249             }
250             return xml;
251         }
252
253         private function serialiseRelation(relation:Relation):XML {
254             var xml:XML = <relation/>
255             serialiseEntity(relation, xml);
256             for ( var i:uint = 0; i < relation.length; i++ ) {
257                 var relMember:RelationMember = relation.getMember(i);
258                 var member:XML = <member/>
259                 member.@ref = relMember.entity.id;
260                 member.@type = relMember.entity.getType();
261                 member.@role = relMember.role;
262                 xml.appendChild(member);
263             }
264             return xml;
265         }
266         
267         private function serialiseEntity(entity:Entity, xml:XML):void {
268             xml.@id = entity.id;
269             xml.@version = entity.version;
270             for each( var tag:Tag in entity.getTagArray() ) {
271               var tagXML:XML = <tag/>
272               tagXML.@k = tag.key;
273               tagXML.@v = tag.value;
274               xml.appendChild(tagXML);
275             }
276         }
277         }
278 }