-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathOsmService.js
More file actions
1895 lines (1571 loc) · 56 KB
/
Copy pathOsmService.js
File metadata and controls
1895 lines (1571 loc) · 56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Extent, Tiler, Viewport, geoZoomToScale, vecAdd } from '@rapid-sdk/math';
import { utilArrayChunk, utilArrayGroupBy, utilArrayUniq, utilObjectOmit, utilQsString } from '@rapid-sdk/util';
import _throttle from 'lodash-es/throttle.js';
import { osmAuth } from 'osm-auth';
import RBush from 'rbush';
import { AbstractSystem } from '../core/AbstractSystem.js';
import { JXON } from '../util/jxon.js';
import { osmEntity, osmNode, osmRelation, osmWay, QAItem } from '../osm/index.js';
import { utilFetchResponse } from '../util/index.js';
/**
* `OsmService`
* This service connects to the OpenStreetMap editing API to perform queries,
* fetch data, upload changesets, and more.
* @see https://wiki.openstreetmap.org/wiki/API
*
* Events available:
* 'apistatuschange'
* 'authLoading'
* 'authDone'
* 'authchange'
* 'loading'
* 'loaded'
* 'loadedNotes'
*/
export class OsmService extends AbstractSystem {
/**
* @constructor
* @param `context` Global shared application context
*/
constructor(context) {
super(context);
this.id = 'osm';
// Some defaults that we will replace with whatever we fetch from the OSM API capabilities result.
this._maxWayNodes = 2000;
this._imageryBlocklists = [/.*\.google(apis)?\..*\/(vt|kh)[\?\/].*([xyz]=.*){3}.*/];
this._wwwroot = 'https://www.openstreetmap.org';
this._apiroot = 'https://api.openstreetmap.org';
this._tileCache = {};
this._noteCache = {};
this._userCache = {};
this._changeset = {};
this._tiler = new Tiler();
this._deferred = new Set();
this._connectionID = 0;
this._tileZoom = 16;
this._noteZoom = 12;
this._apiStatus = null;
this._rateLimit = null;
this._userChangesets = null;
this._userDetails = null;
// Ensure methods used as callbacks always have `this` bound correctly.
this._authLoading = this._authLoading.bind(this);
this._authDone = this._authDone.bind(this);
this._parseCapabilitiesJSON = this._parseCapabilitiesJSON.bind(this);
this._parseCapabilitiesXML = this._parseCapabilitiesXML.bind(this);
this._parseNodeJSON = this._parseNodeJSON.bind(this);
this._parseNodeXML = this._parseNodeXML.bind(this);
this._parseNoteXML = this._parseNoteXML.bind(this);
this._parseRelationJSON = this._parseRelationJSON.bind(this);
this._parseRelationXML = this._parseRelationXML.bind(this);
this._parseUserXML = this._parseUserXML.bind(this);
this._parseWayJSON = this._parseWayJSON.bind(this);
this._parseWayXML = this._parseWayXML.bind(this);
this.reloadApiStatus = this.reloadApiStatus.bind(this);
this.throttledReloadApiStatus = _throttle(this.reloadApiStatus, 500);
// Calculate the deafult OAuth2 `redirect_uri`.
// - `redirect_uri` should be a page that the authorizing server (e.g. `openstreetmap.org`)
// can redirect the user back to as the final step in the OAuth2 handshake.
// - By convention we redirect back to a file `land.html` on the same server that Rapid is served from.
// - The `redirect_uri` value can be overridden by an option to `switchAsync`.
// - Because OAuth2 requires applications to register their allowable `redirect_uri` values,
// there is a short list of `redirect_uris` that will work. Redirecting anywhere else will
// result in "The requested redirect uri is malformed or doesn't match client redirect URI".
// This means:
// - If you have a custom Rapid installed somewhere, you will need to register your own
// OAuth2 application on `openstreetmap.org` for it.
// - If your custom Rapid installation wants to use OSM's dev server 'api06.dev.openstreetmap.org',
// you will need to register a custom application on their dev server too.
// - For more info see: https://github.com/osmlab/osm-auth?tab=readme-ov-file#registering-an-application
let redirect_uri;
const origin = window.location.origin;
// Anything served from `https://mapwith.ai` or `https://rapideditor.org`,
// redirect to the common `/rapid/land.html` on that same origin
if (/^https:\/\/(mapwith\.ai|rapideditor\.org)/i.test(origin)) {
redirect_uri = `${origin}/rapid/land.html`;
// Local testing, redirect to `dist/land.html`
} else if (/^https?:\/\/127.0.0.1:8080/i.test(origin)) {
redirect_uri = `${origin}/dist/land.html`;
// Pick a reasonable default, expect a `land.html` file to exist in the same folder as `index.html`.
// You'll need to register your own OAuth2 application, our OAuth2 application won't redirect to your origin.
} else {
let pathname = window.location.pathname;
let path = pathname.split('/');
if (path.at(-1).includes('.')) { // looks like a filename, like `index.html`
path.pop(); // we want the path without that file
pathname = path.join('/') || '/';
}
if (pathname.charAt(pathname.length - 1) !== '/') {
pathname += '/'; // make sure it ends with '/'
}
redirect_uri = `${origin}${pathname}land.html`;
}
this._oauth = osmAuth({
url: this._wwwroot,
apiUrl: this._apiroot,
client_id: 'O3g0mOUuA2WY5Fs826j5tP260qR3DDX7cIIE2R2WWSc',
client_secret: 'b4aeHD1cNeapPPQTrvpPoExqQRjybit6JBlNnxh62uE',
scope: 'read_prefs write_prefs write_api read_gpx write_notes',
redirect_uri: redirect_uri,
loading: this._authLoading,
done: this._authDone
});
}
/**
* initAsync
* Called after all core objects have been constructed.
* @return {Promise} Promise resolved when this component has completed initialization
*/
initAsync() {
return this.resetAsync();
}
/**
* startAsync
* Called after all core objects have been initialized.
* @return {Promise} Promise resolved when this component has completed startup
*/
startAsync() {
this._started = true;
return Promise.resolve();
}
/**
* resetAsync
* Called after completing an edit session to reset any internal state
* @return {Promise} Promise resolved when this component has completed resetting
*/
resetAsync() {
for (const handle of this._deferred) {
window.cancelIdleCallback(handle);
this._deferred.delete(handle);
}
this._connectionID++;
this._apiStatus = null;
this._rateLimit = null;
this._userChangesets = null;
this._userDetails = null;
if (this._tileCache.inflight) {
Object.values(this._tileCache.inflight).forEach(this._abortRequest);
}
if (this._noteCache.inflight) {
Object.values(this._noteCache.inflight).forEach(this._abortRequest);
}
if (this._noteCache.inflightPost) {
Object.values(this._noteCache.inflightPost).forEach(this._abortRequest);
}
if (this._changeset.inflight) {
this._abortRequest(this._changeset.inflight);
}
this._tileCache = {
lastv: null,
toLoad: new Set(),
loaded: new Set(),
inflight: {},
seen: new Set(),
rbush: new RBush()
};
this._noteCache = {
lastv: null,
toLoad: new Set(),
loaded: new Set(),
inflight: {},
inflightPost: {},
note: {},
closed: {},
rbush: new RBush()
};
this._userCache = {
toLoad: new Set(),
user: {}
};
this._changeset = {};
return Promise.resolve();
}
/**
* switchAsync
* Switch connection and credentials , and reset
* @return {Promise} Promise resolved when this component has completed resetting
*/
switchAsync(newOptions) {
this._wwwroot = newOptions.url;
this._apiroot = newOptions.apiUrl;
// Copy the existing options, but omit 'access_token'.
// (if we did preauth, access_token won't work on a different server)
const oldOptions = utilObjectOmit(this._oauth.options(), 'access_token');
this._oauth.options(Object.assign(oldOptions, newOptions));
return this.resetAsync()
.then(() => {
// causes major issues for the tests
// this.userChangesets(function() {}); // eagerly load user details/changesets
this.emit('authchange');
});
}
get connectionID() {
return this._connectionID;
}
get wwwroot() {
return this._wwwroot;
}
get imageryBlocklists() {
return this._imageryBlocklists;
}
// Returns the maximum number of nodes a single way can have
get maxWayNodes() {
return this._maxWayNodes;
}
changesetURL(changesetID) {
return `${this._wwwroot}/changeset/${changesetID}`;
}
changesetsURL(center, zoom) {
const precision = Math.max(0, Math.ceil(Math.log(zoom) / Math.LN2));
return this._wwwroot + '/history#map=' +
Math.floor(zoom) + '/' +
center[1].toFixed(precision) + '/' +
center[0].toFixed(precision);
}
entityURL(entity) {
const entityID = entity.osmId();
return `${this._wwwroot}/${entity.type}/${entityID}`;
}
historyURL(entity) {
const entityID = entity.osmId();
return `${this._wwwroot}/${entity.type}/${entityID}/history`;
}
userURL(username) {
return `${this._wwwroot}/user/${username}`;
}
noteURL(note) {
return `${this._wwwroot}/note/${note.id}`;
}
noteReportURL(note) {
return `${this._wwwroot}/reports/new?reportable_type=Note&reportable_id=${note.id}`;
}
// Generic method to load data from the OSM API
// Can handle either auth or unauth calls.
loadFromAPI(path, callback, options) {
options = Object.assign({ skipSeen: true }, options);
const cid = this._connectionID;
const gotResult = (err, results) => {
// The user switched connection while the request was inflight
// Ignore results and raise an error.
if (this._connectionID !== cid) {
if (callback) callback({ message: 'Connection Switched', status: -1 });
return;
}
// 400 Bad Request, 401 Unauthorized, 403 Forbidden (while logged in)
// An issue has occurred with the user's credentials.
// Logout and retry the request..
const isAuthenticated = this.authenticated();
if (isAuthenticated && (err?.status === 400 || err?.status === 401 || err?.status === 403)) {
this.logout();
this.loadFromAPI(path, callback, options); // retry
return;
} else { // No retry.. We will relay any error and results to the callback.
if (err) {
// 509 Bandwidth Limit Exceeded, 429 Too Many Requests
if (err.status === 509 || err.status === 429) {
err.response.text() // capture the rate limit details
.then(message => {
let duration = 10; // default 10sec, see if response contains a better value
const match = message.match(/ (\d+) seconds/);
if (match) {
duration = parseInt(match[1], 10);
}
this.setRateLimit(duration);
})
.then(() => this.throttledReloadApiStatus()); // reload status / raise warning
// Some other error.. Note that these are not automatically API issues.
// May be 404 Not Found, etc, but it is worth checking the API status now.
} else {
if (this._apiStatus !== 'error') { // if no error before
this.throttledReloadApiStatus(); // reload status / raise warning
}
}
} else { // no error
if (this._rateLimit) { // if had rate limit before
this._rateLimit = null; // clear rate limit
this.throttledReloadApiStatus(); // reload status / clear warning
}
if (this._apiStatus === 'error') { // if had error before
this.throttledReloadApiStatus(); // reload status / clear warning
}
}
if (callback) {
if (err) {
return callback(err);
} else {
if (path.includes('.json')) {
return this._parseJSON(results, callback, options);
} else {
return this._parseXML(results, callback, options);
}
}
}
}
};
const resource = this._apiroot + path;
const controller = new AbortController();
const _fetch = this.authenticated() ? this._oauth.fetch : window.fetch;
_fetch(resource, { signal: controller.signal })
.then(utilFetchResponse)
.then(result => gotResult(null, result))
.catch(err => {
if (err.name === 'AbortError') return; // ok
gotResult(err); // FetchError or network error (e.g. TypeError from connection timeout)
});
return controller;
}
// Load a single entity by id (ways and relations use the `/full` call to include
// nodes and members). Parent relations are not included, see `loadEntityRelations`.
// GET /api/0.6/node/#id
// GET /api/0.6/[way|relation]/#id/full
loadEntity(id, callback) {
const type = osmEntity.id.type(id); // 'node', 'way', 'relation'
const osmID = osmEntity.id.toOSM(id);
const options = { skipSeen: false };
const full = (type !== 'node' ? '/full' : '');
this.loadFromAPI(
`/api/0.6/${type}/${osmID}${full}.json`,
callback,
options
);
}
// Load a single entity with a specific version
// GET /api/0.6/[node|way|relation]/#id/#version
loadEntityVersion(id, version, callback) {
const type = osmEntity.id.type(id); // 'node', 'way', 'relation'
const osmID = osmEntity.id.toOSM(id);
const options = { skipSeen: false };
this.loadFromAPI(
`/api/0.6/${type}/${osmID}/${version}.json`,
callback,
options
);
}
// Load the relations of a single entity with the given.
// GET /api/0.6/[node|way|relation]/#id/relations
loadEntityRelations(id, callback) {
const type = osmEntity.id.type(id);
const osmID = osmEntity.id.toOSM(id);
const options = { skipSeen: false };
this.loadFromAPI(
`/api/0.6/${type}/${osmID}/relations.json`,
callback,
options
);
}
// Load multiple entities in chunks
// (note: callback may be called multiple times)
// Unlike `loadEntity`, child nodes and members are not fetched
// GET /api/0.6/[nodes|ways|relations]?#parameters
loadMultiple(ids, callback) {
const groups = utilArrayGroupBy(utilArrayUniq(ids), osmEntity.id.type);
const options = { skipSeen: false };
for (const [k, vals] of Object.entries(groups)) {
const type = k + 's'; // nodes, ways, relations
const osmIDs = vals.map(id => osmEntity.id.toOSM(id));
for (const arr of utilArrayChunk(osmIDs, 150)) {
this.loadFromAPI(
`/api/0.6/${type}.json?${type}=` + arr.join(),
callback,
options
);
}
}
}
// Create a changeset
// PUT /api/0.6/changeset/create
createChangeset(changeset, callback) {
if (this._changeset.inflight) {
return callback({ message: 'Changeset already inflight', status: -2 });
} else if (!this.authenticated()) {
return callback({ message: 'Not Authenticated', status: -3 });
}
const createdChangeset = (err, changesetID) => {
this._changeset.inflight = null;
if (err) { return callback(err, changeset); }
this._changeset.openChangesetID = changesetID;
changeset = changeset.update({ id: changesetID });
callback(null, changeset);
};
// try to reuse an existing open changeset
if (this._changeset.openChangesetID) {
return createdChangeset(null, this._changeset.openChangesetID);
}
const errback = this._wrapcb(createdChangeset);
const resource = this._apiroot + '/api/0.6/changeset/create';
const controller = new AbortController();
const options = {
method: 'PUT',
headers: { 'Content-Type': 'text/xml' },
body: JXON.stringify(changeset.asJXON()),
signal: controller.signal
};
this._oauth.fetch(resource, options)
.then(utilFetchResponse)
.then(result => errback(null, result))
.catch(err => {
this._changeset.inflight = null;
if (err.name === 'AbortError') return; // ok
errback(err); // FetchError or network error (e.g. TypeError from connection timeout)
});
this._changeset.inflight = controller;
}
// Upload changes to a changeset
// POST /api/0.6/changeset/#id/upload
uploadChangeset(changeset, changes, callback) {
if (this._changeset.inflight) {
return callback({ message: 'Changeset already inflight', status: -2 });
} else if (!this.authenticated()) {
return callback({ message: 'Not Authenticated', status: -3 });
} else if (changeset.id !== this._changeset.openChangesetID) {
// the given changeset is not open, or a different changeset is open?
return callback({ message: 'Changeset ID mismatch', status: -4 });
}
const uploadedChangeset = (err, /*result*/) => {
this._changeset.inflight = null;
// we do get a changeset diff result, but we don't currently use it for anything
callback(err, changeset);
};
const errback = this._wrapcb(uploadedChangeset);
const resource = this._apiroot + `/api/0.6/changeset/${changeset.id}/upload`;
const controller = new AbortController();
const options = {
method: 'POST',
headers: { 'Content-Type': 'text/xml' },
body: JXON.stringify(changeset.osmChangeJXON(changes)),
signal: controller.signal
};
// Attempt to prevent user from creating duplicate changes - see iD#5200
// Some users will refresh their tab as soon as the changeset is inflight.
// We don't want to offer to restore these same changes when their browser refreshes.
const editor = this.context.systems.editor;
editor.clearBackup();
this._oauth.fetch(resource, options)
.then(utilFetchResponse)
.then(result => errback(null, result))
.catch(err => {
this._changeset.inflight = null;
if (err.name === 'AbortError') return; // ok
errback(err); // FetchError or network error (e.g. TypeError from connection timeout)
});
this._changeset.inflight = controller;
}
// Close a changeset
// PUT /api/0.6/changeset/#id/close
closeChangeset(changeset, callback) {
if (this._changeset.inflight) {
return callback({ message: 'Changeset already inflight', status: -2 });
} else if (!this.authenticated()) {
return callback({ message: 'Not Authenticated', status: -3 });
} else if (changeset.id !== this._changeset.openChangesetID) {
// the given changeset is not open, or a different changeset is open?
return callback({ message: 'Changeset ID mismatch', status: -4 });
}
const closedChangeset = (err, /*result*/) => {
this._changeset.inflight = null;
this._changeset.openChangesetID = null;
// there is no result to this call
callback(err, changeset);
};
const errback = this._wrapcb(closedChangeset);
const resource = this._apiroot + `/api/0.6/changeset/${changeset.id}/close`;
const controller = new AbortController();
const options = {
method: 'PUT',
headers: { 'Content-Type': 'text/xml' },
signal: controller.signal
};
this._oauth.fetch(resource, options)
.then(utilFetchResponse)
.then(result => errback(null, result))
.catch(err => {
this._changeset.inflight = null;
if (err.name === 'AbortError') return; // ok
errback(err); // FetchError or network error (e.g. TypeError from connection timeout)
});
this._changeset.inflight = controller;
}
// Just chains together create, upload, and close a changeset
// PUT /api/0.6/changeset/create
// POST /api/0.6/changeset/#id/upload
// PUT /api/0.6/changeset/#id/close
sendChangeset(changeset, changes, callback) {
const cid = this._connectionID;
this.createChangeset(changeset, (err, updated) => {
changeset = updated;
if (err) { return callback(err, changeset); }
this.uploadChangeset(changeset, changes, (err, updated) => {
changeset = updated;
if (err) { return callback(err, changeset); }
// Upload was successful, it is safe to call the callback.
// Add delay to allow for postgres replication iD#1646 iD#2678
window.setTimeout(() => {
this._changeset.openChangesetID = null;
callback(null, changeset);
}, 2500);
// Closing the changeset is optional, and we won't get a result.
// Only try to close the changeset if we're still talking to the same server.
if (this.connectionID === cid) {
this.closeChangeset(changeset, () => {});
}
});
});
}
// Load multiple users in chunks
// (note: callback may be called multiple times)
// GET /api/0.6/users?users=#id1,#id2,...,#idn
loadUsers(uids, callback) {
let toLoad = [];
let cached = [];
for (const uid of utilArrayUniq(uids)) {
if (this._userCache.user[uid]) { // loaded already
this._userCache.toLoad.delete(uid);
cached.push(this._userCache.user[uid]);
} else {
toLoad.push(uid);
}
}
if (cached.length || !this.authenticated()) {
callback(null, cached);
if (!this.authenticated()) return; // require auth
}
const gotUsers = (err, results) => {
if (err) return callback(err);
callback(null, results.data);
};
const options = { skipSeen: true };
for (const arr of utilArrayChunk(toLoad, 150)) {
this.loadFromAPI(
'/api/0.6/users.json?users=' + arr.join(),
gotUsers,
options
);
}
}
// Load a given user by id
// GET /api/0.6/user/#id
loadUser(uid, callback) {
if (this._userCache.user[uid] || !this.authenticated()) { // require auth
this._userCache.toLoad.delete(uid);
return callback(null, this._userCache.user[uid]);
}
const gotUsers = (err, results) => {
if (err) return callback(err);
callback(null, results.data[0]);
};
const options = { skipSeen: true };
this.loadFromAPI(
`/api/0.6/user/${uid}.json`,
gotUsers,
options
);
}
/**
* _parseUserPreferencesXML
* @param xml
* @param callback
*/
_parseUserPreferencesXML(xml, callback) {
const preferences = {};
const preferenceElems = xml.getElementsByTagName('preference');
for (let i = 0; i < preferenceElems.length; i++) {
const elem = preferenceElems[i];
const key = elem.getAttribute('k');
const value = elem.getAttribute('v');
if (key && value) {
preferences[key] = value;
}
}
callback(null, { data: preferences });
}
// Load maproulette api key from OSM preferences
// GET /api/0.6/user/preferences
loadMapRouletteKey(callback) {
if (!this.authenticated()) { // require auth
return callback(null, {});
}
this._oauth.xhr({
method: 'GET',
path: '/api/0.6/user/preferences'
}, (err, data) => {
if (err) {
console.error('Error in loadUserPreferences:', err); // eslint-disable-line no-console
return callback(err);
}
this._parseUserPreferencesXML(data, (err, result) => {
if (err) {
return callback(err);
} else {
return callback(null, result.data);
}
});
});
}
// Load the details of the logged-in user
// GET /api/0.6/user/details
userDetails(callback) {
if (this._userDetails) { // retrieve cached
return callback(null, this._userDetails);
}
const gotUsers = (err, results) => {
if (err) return callback(err);
this._userDetails = results.data[0];
callback(null, this._userDetails);
};
const options = { skipSeen: false };
this.loadFromAPI(
`/api/0.6/user/details.json`,
gotUsers,
options
);
}
// Load previous changesets for the logged in user
// GET /api/0.6/changesets?user=#id
userChangesets(callback) {
if (this._userChangesets) { // retrieve cached
return callback(null, this._userChangesets);
}
const gotChangesets = (err, results) => {
if (err) return callback(err);
this._userChangesets = results.data;
return callback(null, this._userChangesets);
};
const options = { skipSeen: false };
const gotUser = (err, user) => {
if (err) return callback(err);
this.loadFromAPI(
`/api/0.6/changesets.json?user=${user.id}`,
gotChangesets,
options
);
};
this.userDetails(gotUser);
}
// Fetch the status of the OSM API.
// GET /api/capabilities
// see: https://wiki.openstreetmap.org/wiki/API_v0.6#Response
//
// The status will be one of:
// 'online' - working normally
// 'readonly' - reachable but readonly
// 'offline' - reachable but offline
// 'error' - unreachable / network issue
// 'ratelimit' - rate limit detected
//
status(callback) {
const gotResult = (err, result) => {
if (err?.message === 'Connection Switched') { // If connection was just switched,
this._apiStatus = null; // reset cached status and try again
this.status(callback);
return;
} else if (err) {
return callback(err, 'error'); // a network issue
} else if (this._rateLimit) {
return callback(null, 'ratelimit');
} else {
const status = this._parseCapabilitiesJSON(result);
return callback(null, status);
}
};
const url = this._apiroot + '/api/capabilities.json';
const errback = this._wrapcb(gotResult);
fetch(url, { signal: AbortSignal.timeout(10000) })
.then(utilFetchResponse)
.then(result => errback(null, result))
.catch(err => errback(err));
}
// Calls `status` and emits an `apistatuschange` event if the returned
// status differs from the cached status.
reloadApiStatus() {
this.status((err, result) => {
if (result !== this._apiStatus) {
this._apiStatus = result;
this.emit('apistatuschange', err, result);
}
});
}
// Load data (entities) from the API in tiles
// GET /api/0.6/map?bbox=
loadTiles(callback) {
if (this._paused || this.getRateLimit()) return;
const cache = this._tileCache;
const viewport = this.context.viewport;
if (cache.lastv === viewport.v) return; // exit early if the view is unchanged
cache.lastv = viewport.v;
// Determine the tiles needed to cover the view..
const tiles = this._tiler.zoomRange(this._tileZoom).getTiles(viewport).tiles;
// Abort inflight requests that are no longer needed..
const hadRequests = this._hasInflightRequests(cache);
this._abortUnwantedRequests(cache, tiles);
if (hadRequests && !this._hasInflightRequests(cache)) {
this.emit('loaded'); // stop the spinner
}
// Issue new requests..
for (const tile of tiles) {
this.loadTile(tile, callback);
}
}
/**
* setRateLimit
* This will establish a rate limit for the given duration in seconds.
* If a rate limit already exists, extend the time if needed.
* @param {number} seconds - seconds to impose the rate limit (default 10 sec)
* @return {Object?} rate limit info, or `null` if `seconds` is junk
*/
setRateLimit(seconds = 10) {
// If `seconds` makes no sense, just return the existing rate limit, if any..
if (isNaN(seconds) || !isFinite(seconds) || seconds <= 0) {
return this._rateLimit;
}
// If rate limit already exists for a longer duration, do nothing..
if (this._rateLimit && this._rateLimit.remaining >= seconds) {
return this._rateLimit;
}
// Stop loading tiles, and cancel any inflight
this._tileCache.toLoad.clear();
this._noteCache.toLoad.clear();
Object.values(this._tileCache.inflight).forEach(this._abortRequest);
Object.values(this._noteCache.inflight).forEach(this._abortRequest);
return this._rateLimit = {
start: Math.floor(Date.now() / 1000), // epoch seconds
duration: seconds, // retry-after seconds
remaining: seconds,
elapsed: 0
};
}
/**
* getRateLimit
* If there is currently a rate limit, return the information about it.
* This will also cancel the rate limit if we detect that it has expired.
* @return {Object?} rate limit info, or `null` if no current rate limit
*/
getRateLimit() {
if (!this._rateLimit) return null;
const now = Math.floor(Date.now() / 1000); // epoch seconds
const start = this._rateLimit.start ?? now;
const duration = this._rateLimit.duration ?? 10;
let elapsed = now - start;
// Check if something unexpected moved the clock more than 5 seconds backwards
if (elapsed < -5) { // leap seconds? epoch rollover? time travel?
this._rateLimit.start = now; // restart the counter
elapsed = 0;
}
const remaining = duration - elapsed;
if (remaining > 0) {
this._rateLimit.remaining = remaining;
this._rateLimit.elapsed = elapsed;
return this._rateLimit;
} else {
this._rateLimit = null; // rate limit is over
return null;
}
}
// Load a single data tile
// GET /api/0.6/map?bbox=
loadTile(tile, callback) {
if (this._paused || this.getRateLimit()) return;
const cache = this._tileCache;
if (cache.loaded.has(tile.id) || cache.inflight[tile.id]) return;
// Exit if this tile covers a blocked region (all corners are blocked)
const locations = this.context.systems.locations;
const corners = tile.wgs84Extent.polygon().slice(0, 4);
const tileBlocked = corners.every(loc => locations.blocksAt(loc).length);
if (tileBlocked) {
cache.loaded.add(tile.id); // don't try again
return;
}
if (!this._hasInflightRequests(cache)) {
this.emit('loading'); // start the spinner
}
const gotTile = (err, results) => {
delete cache.inflight[tile.id];
if (!err) {
cache.toLoad.delete(tile.id);
cache.loaded.add(tile.id);
const bbox = tile.wgs84Extent.bbox();
bbox.id = tile.id;
cache.rbush.insert(bbox);
}
if (callback) {
callback(err, Object.assign({}, results, { tile: tile }));
}
if (!this._hasInflightRequests(cache)) {
this.emit('loaded'); // stop the spinner
}
};
const path = '/api/0.6/map.json?bbox=';
const options = { skipSeen: true };
cache.inflight[tile.id] = this.loadFromAPI(
path + tile.wgs84Extent.toParam(),
gotTile,
options
);
}
isDataLoaded(loc) {
const bbox = { minX: loc[0], minY: loc[1], maxX: loc[0], maxY: loc[1] };
return this._tileCache.rbush.collides(bbox);
}
// Load the tile that covers the given `loc`
loadTileAtLoc(loc, callback) {
if (this._paused || this.getRateLimit()) return;
const cache = this._tileCache;
// Back off if the toLoad queue is filling up.. re iD#6417
// (Currently `loadTileAtLoc` requests are considered low priority - used by operations to
// let users safely edit geometries which extend to unloaded tiles. We can drop some.)
if (cache.toLoad.size > 50) return;
const k = geoZoomToScale(this._tileZoom + 1);
const offset = new Viewport({ k: k }).project(loc);
const viewport = new Viewport({ k: k, x: -offset[0], y: -offset[1] });
const tiles = this._tiler.zoomRange(this._tileZoom).getTiles(viewport).tiles;
for (const tile of tiles) {
if (cache.toLoad.has(tile.id) || cache.loaded.has(tile.id) || cache.inflight[tile.id]) continue;
cache.toLoad.add(tile.id);
this.loadTile(tile, callback);
}
}
// Load notes from the API in tiles
// GET /api/0.6/notes?bbox=
loadNotes(noteOptions) {
if (this._paused || this.getRateLimit()) return;
noteOptions = Object.assign({ limit: 10000, closed: 7 }, noteOptions);