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