Remove all public references to the appID/OAuthConsumer object
[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     /**
12     * XMLConnection provides all the methods required to connect to a live
13     * OSM server. See OSMConnection for connecting to a read-only .osm file
14     */
15         public class XMLConnection extends XMLBaseConnection {
16
17         //public var readConnection:NetConnection;
18
19                 public function XMLConnection() {
20
21                         if (Connection.policyURL!='')
22                 Security.loadPolicyFile(Connection.policyURL);
23             var oauthPolicy:String = Connection.getParam("oauth_policy", "");
24             if ( oauthPolicy != "" ) {
25                 Security.loadPolicyFile(oauthPolicy);
26             }
27                 }
28                 
29                 override public function loadBbox(left:Number,right:Number,
30                                                                 top:Number,bottom:Number):void {
31             var mapVars:URLVariables = new URLVariables();
32             mapVars.bbox= left+","+bottom+","+right+","+top;
33
34             var mapRequest:URLRequest = new URLRequest(Connection.apiBaseURL+"map");
35             mapRequest.data = mapVars;
36
37             var mapLoader:URLLoader = new URLLoader();
38             mapLoader.addEventListener(Event.COMPLETE, loadedMap);
39             mapLoader.addEventListener(IOErrorEvent.IO_ERROR, errorOnMapLoad);
40             mapLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, mapLoadStatus);
41             mapLoader.load(mapRequest);
42             dispatchEvent(new Event(LOAD_STARTED));
43                 }
44
45         private function errorOnMapLoad(event:Event):void {
46                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't load the map" } ));
47         }
48         private function mapLoadStatus(event:HTTPStatusEvent):void {
49             trace("loading map status = "+event.status);
50         }
51
52         protected var appID:OAuthConsumer;
53         protected var authToken:OAuthToken;
54
55             override public function setAuthToken(id:Object):void {
56                 authToken = OAuthToken(id);
57             }
58
59         /* Get the stored access token, or try setting it up from loader params or passed SharedObject */
60         /* todo: make this private */
61         override public function getAccessToken(data:Object):OAuthToken {
62             if (authToken == null) {
63               var key:String = getParam("oauth_token", null);
64               var secret:String = getParam("oauth_token_secret", null);
65
66               if ( key == null || secret == null ) {
67                   key = data["oauth_token"];
68                   secret = data["oauth_token_secret"];
69               }
70
71               if ( key != null && secret != null ) {
72                   authToken = new OAuthToken(key, secret);
73               }
74             }
75             return authToken;
76         }
77
78         private function getConsumer():OAuthConsumer {
79             if (appID == null) {
80               var key:String = getParam("oauth_consumer_key", null);
81               var secret:String = getParam("oauth_consumer_secret", null);
82
83               if ( key != null && secret != null ) {
84                   appID = new OAuthConsumer(key, secret);
85               }
86             }
87             return appID;
88         }
89
90         private var httpStatus:int = 0;
91         
92         private function recordStatus(event:HTTPStatusEvent):void {
93             httpStatus = event.status;
94         }
95         
96         private var lastUploadedChangesetTags:Object;
97         
98         override public function createChangeset(tags:Object):void {
99             lastUploadedChangesetTags = tags;
100             
101                 var changesetXML:XML = <osm version="0.6"><changeset /></osm>;
102                 var changeset:XML = <changeset />;
103                 for (var tagKey:Object in tags) {
104               var tagXML:XML = <tag/>;
105               tagXML.@k = tagKey;
106               tagXML.@v = tags[tagKey];
107               changesetXML.changeset.appendChild(tagXML);
108             }        
109
110                         sendOAuthPut(Connection.apiBaseURL+"changeset/create",
111                                                  changesetXML,
112                                                  changesetCreateComplete, changesetCreateError, recordStatus);
113             }
114
115         private function changesetCreateComplete(event:Event):void {
116             // response should be a Number changeset id
117             var id:Number = Number(URLLoader(event.target).data);
118             
119             // which means we now have a new changeset!
120             setActiveChangeset(new Changeset(id, lastUploadedChangesetTags));
121         }
122
123         private function changesetCreateError(event:IOErrorEvent):void {
124             dispatchEvent(new Event(NEW_CHANGESET_ERROR));
125         }
126
127                 override public function closeChangeset():void {
128             var cs:Changeset = getActiveChangeset();
129                         if (!cs) return;
130                         
131                         sendOAuthPut(Connection.apiBaseURL+"changeset/"+cs.id+"/close",
132                                                  null,
133                                                  changesetCloseComplete, changesetCloseError, recordStatus);
134                         closeActiveChangeset();
135                 }
136                 
137                 private function changesetCloseComplete(event:Event):void { }
138                 private function changesetCloseError(event:Event):void { }
139                 // ** TODO: when we get little floating warnings, we can send a happy or sad one up
140
141         private function signedOAuthURL(url:String, method:String):String {
142             // method should be PUT, GET, POST or DELETE
143             var sig:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
144             var oauthRequest:OAuthRequest = new OAuthRequest(method, url, null, getConsumer(), authToken);
145             var urlStr:Object = oauthRequest.buildRequest(sig, OAuthRequest.RESULT_TYPE_URL_STRING);
146             return String(urlStr);
147         }
148
149                 private function sendOAuthPut(url:String, xml:XML, onComplete:Function, onError:Function, onStatus:Function):void {
150             // build the request
151             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "PUT"));
152             urlReq.method = "POST";
153                         if (xml) { urlReq.data = xml.toXMLString(); } else { urlReq.data = true; }
154             urlReq.contentType = "application/xml";
155             urlReq.requestHeaders = new Array(new URLRequestHeader("X_HTTP_METHOD_OVERRIDE", "PUT"));
156             var loader:URLLoader = new URLLoader();
157             loader.addEventListener(Event.COMPLETE, onComplete);
158             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
159             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
160                 loader.load(urlReq);
161                 }
162
163         private function sendOAuthGet(url:String, onComplete:Function, onError:Function, onStatus:Function):void {
164             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "GET"));
165             urlReq.method = "GET";
166             var loader:URLLoader = new URLLoader();
167             loader.addEventListener(Event.COMPLETE, onComplete);
168             loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
169             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);
170             loader.load(urlReq);
171         }
172
173         override public function uploadChanges():void {
174             var changeset:Changeset = getActiveChangeset();
175             var upload:XML = <osmChange version="0.6"/>
176             upload.appendChild(addCreated(changeset, getAllNodeIDs, getNode, serialiseNode));
177             upload.appendChild(addCreated(changeset, getAllWayIDs, getWay, serialiseWay));
178             upload.appendChild(addCreated(changeset, getAllRelationIDs, getRelation, serialiseRelation));
179             upload.appendChild(addModified(changeset, getAllNodeIDs, getNode, serialiseNode));
180             upload.appendChild(addModified(changeset, getAllWayIDs, getWay, serialiseWay));
181             upload.appendChild(addModified(changeset, getAllRelationIDs, getRelation, serialiseRelation));
182             upload.appendChild(addDeleted(changeset, getAllRelationIDs, getRelation, serialiseEntityRoot));
183             upload.appendChild(addDeleted(changeset, getAllWayIDs, getWay, serialiseEntityRoot));
184             upload.appendChild(addDeleted(changeset, getAllNodeIDs, getNode, serialiseEntityRoot));
185
186             // now actually upload them
187             // make an OAuth query
188
189             var url:String = Connection.apiBaseURL+"changeset/" + changeset.id + "/upload";
190
191             // build the actual request
192             var urlReq:URLRequest = new URLRequest(signedOAuthURL(url, "POST"));
193             urlReq.method = "POST";
194             urlReq.data = upload.toXMLString();
195             urlReq.contentType = "text/xml";
196             var loader:URLLoader = new URLLoader();
197             loader.addEventListener(Event.COMPLETE, diffUploadComplete);
198             loader.addEventListener(IOErrorEvent.IO_ERROR, diffUploadError);
199             loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, recordStatus);
200                 loader.load(urlReq);
201                 
202                 dispatchEvent(new Event(SAVE_STARTED));
203         }
204
205         private function diffUploadComplete(event:Event):void {
206             // response should be XML describing the progress
207             var results:XML = new XML((URLLoader(event.target).data));
208             
209             for each( var update:XML in results.child("*") ) {
210                 var oldID:Number = Number(update.@old_id);
211                 var newID:Number = Number(update.@new_id);
212                 var version:uint = uint(update.@new_version);
213                 var type:String = update.name();
214
215                                 if (newID==0) {
216                                         // delete
217                         if ( type == "node" ) killNode(oldID);
218                         else if ( type == "way" ) killWay(oldID);
219                         else if ( type == "relation" ) killRelation(oldID);
220                                         
221                                 } else {
222                                         // create/update
223                         var entity:Entity;
224                         if ( type == "node" ) entity = getNode(oldID);
225                         else if ( type == "way" ) entity = getWay(oldID);
226                         else if ( type == "relation" ) entity = getRelation(oldID);
227                         entity.markClean(newID, version);
228                 
229                         if ( oldID != newID ) {
230                             if ( type == "node" ) renumberNode(oldID, entity as Node, false);
231                             else if ( type == "way" ) renumberWay(oldID, entity as Way, false);
232                             else if ( type == "relation" ) renumberRelation(oldID, entity as Relation, false);
233                         }
234                                 }
235             }
236
237             dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, true));
238                         freshenActiveChangeset();
239             markClean(); // marks the connection clean. Pressing undo from this point on leads to unexpected results
240             MainUndoStack.getGlobalStack().breakUndo(); // so, for now, break the undo stack
241         }
242
243         private function diffUploadError(event:IOErrorEvent):void {
244                         dispatchEvent(new MapEvent(MapEvent.ERROR, { message: "Couldn't upload data: "+httpStatus+" "+event.text } ));
245                 dispatchEvent(new SaveCompleteEvent(SAVE_COMPLETED, false));
246         }
247
248         private function addCreated(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
249             var create:XML = <create version="0.6"/>
250             for each( var id:Number in getIDs() ) {
251                 var entity:Entity = get(id);
252                 if ( id >= 0 || entity.deleted )
253                     continue;
254                     
255                 var xml:XML = serialise(entity);
256                 xml.@changeset = changeset.id;
257                 create.appendChild(xml);
258             }
259             return create.hasComplexContent() ? create : <!-- blank create section -->;
260         }
261
262                 private function addDeleted(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
263             var del:XML = <delete version="0.6"/>
264             for each( var id:Number in getIDs() ) {
265                 var entity:Entity = get(id);
266                 // creates are already included
267                 if ( id < 0 || !entity.deleted )
268                     continue;
269                     
270                 var xml:XML = serialise(entity);
271                 xml.@changeset = changeset.id;
272                 del.appendChild(xml);
273             }
274             return del.hasComplexContent() ? del : <!-- blank delete section -->;
275                 }
276
277         private function addModified(changeset:Changeset, getIDs:Function, get:Function, serialise:Function):XML {
278             var modify:XML = <modify version="0.6"/>
279             for each( var id:Number in getIDs() ) {
280                 var entity:Entity = get(id);
281                 // creates and deletes are already included
282                 if ( id < 0 || entity.deleted || !entity.isDirty )
283                     continue;
284                     
285                 var xml:XML = serialise(entity);
286                 xml.@changeset = changeset.id;
287                 modify.appendChild(xml);
288             }
289             return modify.hasComplexContent() ? modify : <!-- blank modify section -->;
290         }
291
292         private function serialiseNode(node:Node):XML {
293             var xml:XML = serialiseEntityRoot(node); //<node/>
294             serialiseEntityTags(node, xml);
295             xml.@lat = node.lat;
296             xml.@lon = node.lon;
297             return xml;
298         }
299
300         private function serialiseWay(way:Way):XML {
301             var xml:XML = serialiseEntityRoot(way); //<node/>
302             serialiseEntityTags(way, xml);
303             for ( var i:uint = 0; i < way.length; i++ ) {
304                 var nd:XML = <nd/>
305                 nd.@ref = way.getNode(i).id;
306                 xml.appendChild(nd);
307             }
308             return xml;
309         }
310
311         private function serialiseRelation(relation:Relation):XML {
312             var xml:XML = serialiseEntityRoot(relation); //<node/>
313             serialiseEntityTags(relation, xml);
314             for ( var i:uint = 0; i < relation.length; i++ ) {
315                 var relMember:RelationMember = relation.getMember(i);
316                 var member:XML = <member/>
317                 member.@ref = relMember.entity.id;
318                 member.@type = relMember.entity.getType();
319                 member.@role = relMember.role;
320                 xml.appendChild(member);
321             }
322             return xml;
323         }
324         
325                 private function serialiseEntityRoot(entity:Object):XML {
326                         var xml:XML;
327                         if      (entity is Way     ) { xml = <way/> }
328                         else if (entity is Node    ) { xml = <node/> }
329                         else if (entity is Relation) { xml = <relation/> }
330                         xml.@id = entity.id;
331                         xml.@version = entity.version;
332                         return xml;
333                 }
334
335         private function serialiseEntityTags(entity:Entity, xml:XML):void {
336             xml.@id = entity.id;
337             xml.@version = entity.version;
338             for each( var tag:Tag in entity.getTagArray() ) {
339               if (tag.key == 'created_by') {
340                 entity.setTag('created_by', null, MainUndoStack.getGlobalStack().addAction);
341                 continue;
342               }
343               var tagXML:XML = <tag/>
344               tagXML.@k = tag.key;
345               tagXML.@v = tag.value;
346               xml.appendChild(tagXML);
347             }
348         }
349
350         override public function fetchUserTraces(refresh:Boolean=false):void {
351             if (traces_loaded && !refresh) {
352               dispatchEvent(new Event(TRACES_LOADED));
353             } else {
354               sendOAuthGet(Connection.apiBaseURL+"user/gpx_files",
355                           tracesLoadComplete, errorOnMapLoad, mapLoadStatus); //needs error handlers
356               dispatchEvent(new Event(LOAD_STARTED)); //specific to map or reusable?
357             }
358         }
359
360         private function tracesLoadComplete(event:Event):void {
361             clearTraces();
362             var files:XML = new XML(URLLoader(event.target).data);
363             for each(var traceData:XML in files.gpx_file) {
364               var t:Trace = new Trace().fromXML(traceData);
365               addTrace(t);
366             }
367             traces_loaded = true;
368             dispatchEvent(new Event(LOAD_COMPLETED));
369             dispatchEvent(new Event(TRACES_LOADED));
370         }
371
372         override public function fetchTrace(id:Number, callback:Function):void {
373             sendOAuthGet(Connection.apiBaseURL+"gpx/"+id+"/data.xml", callback, errorOnMapLoad, mapLoadStatus); // needs error handlers
374             dispatchEvent(new Event(LOAD_STARTED)); //specifc to map or reusable?
375         }
376         }
377 }