Store the returned traces in the connection, and provide accessor methods for retrieval.
[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         private function sendOAuthGet(url:String, onComplete:Function, onError:Function, onStatus:Function):void {
130             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
131             var oauthRequest:OAuthRequest = new OAuthRequest("GET", url, null, appID, authToken);
132             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING);
133
134             var urlReq:URLRequest = new URLRequest(String(urlStr));
135             urlReq.method = "GET";
136             var loader:URLLoader = new URLLoader();
137             loader.addEventListener(Event.COMPLETE, onComplete);
138             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
139             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
140             loader.load(urlReq);
141         }
142         
143         override public function uploadChanges():void {
144             var changeset:Changeset = getActiveChangeset();
145             var upload:XML = <osmChange version="0.6"/>
146             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
147             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
148             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
149             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
150             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
151             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
152             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot));
153             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot));
154             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot));
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                                 if (newID==0) {
188                                         // delete
189                         if ( type == "node" ) killNode(oldID);
190                         else if ( type == "way" ) killWay(oldID);
191                         else if ( type == "relation" ) killRelation(oldID);
192                                         
193                                 } else {
194                                         // create/update
195                         var entity:Entity;
196                         if ( type == "node" ) entity = getNode(oldID);
197                         else if ( type == "way" ) entity = getWay(oldID);
198                         else if ( type == "relation" ) entity = getRelation(oldID);
199                         entity.markClean(newID, version);
200                 
201                         if ( oldID != newID ) {
202                             if ( type == "node" ) renumberNode(oldID, entity as Node, false);
203                             else if ( type == "way" ) renumberWay(oldID, entity as Way, false);
204                             else if ( type == "relation" ) renumberRelation(oldID, entity as Relation, false);
205                         }
206                                 }
207             }
208
209             dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
210                         freshenActiveChangeset();
211             markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
212             MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
213         }
214
215         private function diffUploadError(event:IOErrorEvent):void {
216                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+httpStatus+" "+event.text } ));
217                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
218         }
219
220         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
221             var create:XML = <create version="0.6"/>
222             for each( var id:Number in getIDs() ) {
223                 var entity:Entity = get(id);
224                 if ( id >= 0 || entity.deleted )
225                     continue;
226                     
227                 var xml:XML = serialise(entity);
228                 xml.@changeset = changeset.id;
229                 create.appendChild(xml);
230             }
231             return create.hasComplexContent() ? create : <!-- blank create section -->;
232         }
233
234                 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
235             var del:XML = <delete version="0.6"/>
236             for each( var id:Number in getIDs() ) {
237                 var entity:Entity = get(id);
238                 // creates are already included
239                 if ( id < 0 || !entity.deleted )
240                     continue;
241                     
242                 var xml:XML = serialise(entity);
243                 xml.@changeset = changeset.id;
244                 del.appendChild(xml);
245             }
246             return del.hasComplexContent() ? del : <!-- blank delete section -->;
247                 }
248
249         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
250             var modify:XML = <modify version="0.6"/>
251             for each( var id:Number in getIDs() ) {
252                 var entity:Entity = get(id);
253                 // creates and deletes are already included
254                 if ( id < 0 || entity.deleted || !entity.isDirty )
255                     continue;
256                     
257                 var xml:XML = serialise(entity);
258                 xml.@changeset = changeset.id;
259                 modify.appendChild(xml);
260             }
261             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
262         }
263
264         private function serialiseNode(node:Node):XML {
265             var xml:XML = serialiseEntityRoot(node); //<node/>
266             serialiseEntityTags(node, xml);
267             xml.@lat = node.lat;
268             xml.@lon = node.lon;
269             return xml;
270         }
271
272         private function serialiseWay(way:Way):XML {
273             var xml:XML = serialiseEntityRoot(way); //<node/>
274             serialiseEntityTags(way, xml);
275             for ( var i:uint = 0; i < way.length; i++ ) {
276                 var nd:XML = <nd/>
277                 nd.@ref = way.getNode(i).id;
278                 xml.appendChild(nd);
279             }
280             return xml;
281         }
282
283         private function serialiseRelation(relation:Relation):XML {
284             var xml:XML = serialiseEntityRoot(relation); //<node/>
285             serialiseEntityTags(relation, xml);
286             for ( var i:uint = 0; i < relation.length; i++ ) {
287                 var relMember:RelationMember = relation.getMember(i);
288                 var member:XML = <member/>
289                 member.@ref = relMember.entity.id;
290                 member.@type = relMember.entity.getType();
291                 member.@role = relMember.role;
292                 xml.appendChild(member);
293             }
294             return xml;
295         }
296         
297                 private function serialiseEntityRoot(entity:Object):XML {
298                         var xml:XML;
299                         if      (entity is Way     ) { xml = <way/> }
300                         else if (entity is Node    ) { xml = <node/> }
301                         else if (entity is Relation) { xml = <relation/> }
302                         xml.@id = entity.id;
303                         xml.@version = entity.version;
304                         return xml;
305                 }
306
307         private function serialiseEntityTags(entity:Entity, xml:XML):void {
308             xml.@id = entity.id;
309             xml.@version = entity.version;
310             for each( var tag:Tag in entity.getTagArray() ) {
311               var tagXML:XML = <tag/>
312               tagXML.@k = tag.key;
313               tagXML.@v = tag.value;
314               xml.appendChild(tagXML);
315             }
316         }
317
318         override public function fetchUserTraces():void {
319             sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
320                          tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
321             dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
322         }
323
324         private function tracesLoadComplete(event:Event):void {
325             //for each result in XML file
326             //  create a trace object
327             //  store in connection.traces
328             //emit event
329             var files:XML = new XML(URLLoader(event.target).data);
330             for each(var traceData:XML in files.gpx_file) {
331               var t:Object = {};
332               t.id = traceData.@id;
333               t.name = traceData.@name;
334               t.url = Connection.apiBaseURL+"gpx/"+t.id+"/data";
335               addTrace(t);
336             }
337             trace("loaded gpx files");
338             dispatchEvent(new Event(TRACES_LOADED));
339         }
340         }
341 }