press S to save, C to close changeset
[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         public class XMLConnection extends XMLBaseConnection {
12
13         //public var readConnection:NetConnection;
14
15                 public function XMLConnection() {
16
17                         if (Connection.policyURL!='')
18                 Security.loadPolicyFile(Connection.policyURL);
19             var oauthPolicy:String = Connection.getParam("oauth_policy", "");
20             if ( 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.addEventListener(IOErrorEvent.IO_ERROR, errorOnMapLoad);
36             mapLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, mapLoadStatus);
37             mapLoader.load(mapRequest);
38             dispatchEvent(new Event(LOAD_STARTED));
39                 }
40
41         private function errorOnMapLoad(event:Event):void {
42                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't load the map" } ));
43         }
44         private function mapLoadStatus(event:HTTPStatusEvent):void {
45             trace("loading map status = "+event.status);
46         }
47
48         protected var appID:OAuthConsumer;
49         protected var authToken:OAuthToken;
50         
51             override public function setAppID(id:Object):void {
52                 appID = OAuthConsumer(id);
53             }
54             
55             override public function setAuthToken(id:Object):void {
56                 authToken = OAuthToken(id);
57             }
58
59         private var httpStatus:int = 0;
60         
61         private function recordStatus(event:HTTPStatusEvent):void {
62             httpStatus = event.status;
63         }
64         
65         private var lastUploadedChangesetTags:Object;
66         
67         override public function createChangeset(tags:Object):void {
68             lastUploadedChangesetTags = tags;
69             
70                 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
71                 var changeset:XML = <changeset />;
72                 for (var tagKey:Object in tags) {
73               var tagXML:XML = <tag/>;
74               tagXML.@k = tagKey;
75               tagXML.@v = tags[tagKey];
76               changesetXML.changeset.appendChild(tagXML);
77             }        
78
79                         sendOAuthPut(Connection.apiBaseURL+"changeset/create",
80                                                  changesetXML,
81                                                  changesetCreateComplete, changesetCreateError, recordStatus);
82             }
83
84         private function changesetCreateComplete(event:Event):void {
85             // response should be a Number changeset id
86             var id:Number = Number(URLLoader(event.target).data);
87             
88             // which means we now have a new changeset!
89             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
90         }
91
92         private function changesetCreateError(event:IOErrorEvent):void {
93             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
94         }
95
96                 override public function closeChangeset():void {
97             var cs:Changeset = getActiveChangeset();
98                         if (!cs) return;
99                         
100                         sendOAuthPut(Connection.apiBaseURL+"changeset/"+cs.id+"/close",
101                                                  null,
102                                                  changesetCloseComplete, changesetCloseError, recordStatus);
103                         closeActiveChangeset();
104                 }
105                 
106                 private function changesetCloseComplete(event:Event):void { }
107                 private function changesetCloseError(event:Event):void { }
108                 // ** TODO: when we get little floating warnings, we can send a happy or sad one up
109
110                 private function sendOAuthPut(url:String, xml:XML, onComplete:Function, onError:Function, onStatus:Function):void {
111             // make an OAuth query
112             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
113             var oauthRequest:OAuthRequest = new OAuthRequest("PUT", url, null, appID, authToken);
114             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
115
116             // build the actual request
117             var urlReq:URLRequest = new URLRequest(String(urlStr));
118             urlReq.method = "POST";
119                         if (xml) { urlReq.data = xml.toXMLString(); } else { urlReq.data = true; }
120             urlReq.contentType = "application/xml";
121             urlReq.requestHeaders = new Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
122             var loader:URLLoader = new URLLoader();
123             loader.addEventListener(Event.COMPLETE, onComplete);
124             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
125             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
126                 loader.load(urlReq);
127                 }
128         
129         override public function uploadChanges():void {
130             var changeset:Changeset = getActiveChangeset();
131             var upload:XML = <osmChange version="0.6"/>
132             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
133             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
134             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
135             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
136             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
137             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
138             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot));
139             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot));
140             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot));
141
142             // now actually upload them
143             // make an OAuth query
144             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
145             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
146             var oauthRequest:OAuthRequest = new OAuthRequest("POST", url, null, appID, authToken);
147             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING)
148
149             // build the actual request
150             var urlReq:URLRequest = new URLRequest(String(urlStr));
151             urlReq.method = "POST";
152             urlReq.data = upload.toXMLString();
153             urlReq.contentType = "text/xml";
154             var loader:URLLoader = new URLLoader();
155             loader.addEventListener(Event.COMPLETE, diffUploadComplete);
156             loader.addEventListener(IOErrorEvent.IO_ERROR, diffUploadError);
157             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
158                 loader.load(urlReq);
159                 
160                 dispatchEvent(new Event(SAVE_STARTED));
161         }
162
163         private function diffUploadComplete(event:Event):void {
164             // response should be XML describing the progress
165             var results:XML = new XML((URLLoader(event.target).data));
166             
167             for each( var update:XML in results.child("*") ) {
168                 var oldID:Number = Number(update.@old_id);
169                 var newID:Number = Number(update.@new_id);
170                 var version:uint = uint(update.@new_version);
171                 var type:String = update.name();
172
173                                 if (newID==0) {
174                                         // delete
175                         if ( type == "node" ) killNode(oldID);
176                         else if ( type == "way" ) killWay(oldID);
177                         else if ( type == "relation" ) killRelation(oldID);
178                                         
179                                 } else {
180                                         // create/update
181                         var entity:Entity;
182                         if ( type == "node" ) entity = getNode(oldID);
183                         else if ( type == "way" ) entity = getWay(oldID);
184                         else if ( type == "relation" ) entity = getRelation(oldID);
185                         entity.markClean(newID, version);
186                 
187                         if ( oldID != newID ) {
188                             if ( type == "node" ) renumberNode(oldID, entity as Node, false);
189                             else if ( type == "way" ) renumberWay(oldID, entity as Way, false);
190                             else if ( type == "relation" ) renumberRelation(oldID, entity as Relation, false);
191                         }
192                                 }
193             }
194
195             dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
196                         freshenActiveChangeset();
197             markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
198             MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
199         }
200
201         private function diffUploadError(event:IOErrorEvent):void {
202                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+httpStatus+" "+event.text } ));
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                 var entity:Entity = get(id);
210                 if ( id >= 0 || entity.deleted )
211                     continue;
212                     
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 addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
221             var del:XML = <delete 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.deleted )
226                     continue;
227                     
228                 var xml:XML = serialise(entity);
229                 xml.@changeset = changeset.id;
230                 del.appendChild(xml);
231             }
232             return del.hasComplexContent() ? del : <!-- blank delete section -->;
233                 }
234
235         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
236             var modify:XML = <modify version="0.6"/>
237             for each( var id:Number in getIDs() ) {
238                 var entity:Entity = get(id);
239                 // creates and deletes are already included
240                 if ( id < 0 || entity.deleted || !entity.isDirty )
241                     continue;
242                     
243                 var xml:XML = serialise(entity);
244                 xml.@changeset = changeset.id;
245                 modify.appendChild(xml);
246             }
247             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
248         }
249
250         private function serialiseNode(node:Node):XML {
251             var xml:XML = serialiseEntityRoot(node); //<node/>
252             serialiseEntityTags(node, xml);
253             xml.@lat = node.lat;
254             xml.@lon = node.lon;
255             return xml;
256         }
257
258         private function serialiseWay(way:Way):XML {
259             var xml:XML = serialiseEntityRoot(way); //<node/>
260             serialiseEntityTags(way, xml);
261             for ( var i:uint = 0; i < way.length; i++ ) {
262                 var nd:XML = <nd/>
263                 nd.@ref = way.getNode(i).id;
264                 xml.appendChild(nd);
265             }
266             return xml;
267         }
268
269         private function serialiseRelation(relation:Relation):XML {
270             var xml:XML = serialiseEntityRoot(relation); //<node/>
271             serialiseEntityTags(relation, xml);
272             for ( var i:uint = 0; i < relation.length; i++ ) {
273                 var relMember:RelationMember = relation.getMember(i);
274                 var member:XML = <member/>
275                 member.@ref = relMember.entity.id;
276                 member.@type = relMember.entity.getType();
277                 member.@role = relMember.role;
278                 xml.appendChild(member);
279             }
280             return xml;
281         }
282         
283                 private function serialiseEntityRoot(entity:Object):XML {
284                         var xml:XML;
285                         if      (entity is Way     ) { xml = <way/> }
286                         else if (entity is Node    ) { xml = <node/> }
287                         else if (entity is Relation) { xml = <relation/> }
288                         xml.@id = entity.id;
289                         xml.@version = entity.version;
290                         return xml;
291                 }
292
293         private function serialiseEntityTags(entity:Entity, xml:XML):void {
294             xml.@id = entity.id;
295             xml.@version = entity.version;
296             for each( var tag:Tag in entity.getTagArray() ) {
297               var tagXML:XML = <tag/>
298               tagXML.@k = tag.key;
299               tagXML.@v = tag.value;
300               xml.appendChild(tagXML);
301             }
302         }
303
304         }
305 }