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